title: How to make a wait timer?

text:
# Question
Title: How to make a wait timer?
I am making a mining styled game and am looking to make variables that effect how fast you are able to mine the block. This is the idea I have currently got but it does not wait for the timer to complete before mining, has anyone got a better way to do this?

```
        if (MinePlayerCollision() && newState.IsKeyDown(Keys.D))
        {
            MiningElapsed = (float) gameTime.TotalGameTime.Seconds;

            if (MiningEff <= MiningElapsed)
            {
                BlockMined = true;
                MineReset = false;

                MiningElapsed = 0;
            }
        }

```

# Answer
> 1 votes
A health/damage mining system would be much more flexible and should be easier to implement than a fixed, time-based system. Basically, assign each block a health value, and your pickaxe a "mining damage" value, and whenever the pick strikes the block, you subtract its damage from the health of the block. When the block's health goes to zero or below, the block is mined. In order to achieve a certain time span until a certain block of ore is mined, then set the block's health equal to *damage per pick strike* * *pick strikes per second*

Advantage: You can re-use the existing health system for all your other entities, if you have one, and you can much more easily introduce and balance kinds of ores that are easy/hard to mine and pickaxes of different strengths. You can also give your players more flexibility in what tools they use for different tasks. For example, why not allow your players to mine ores with dynamite, i.e. explosive damage, instead of only pickaxes? A health/damage system allows you to do that quite easily.

# Answer
> 0 votes
So you are on the right track but using not understanding what some of the parts of your code do.

## GameTime.TotalGameTime Property

> Game time since the start of the game.

## GameTime.ElapsedGameTime

> Elapsed game time since the last update.

`MiningElapsed` is currently set to the number of seconds since your game started. As a result its always going to become and stay larger than MiningEff. What you want to use is the time delta `gameTime.ElapsedGameTime`.

```
    if (MinePlayerCollision() && newState.IsKeyDown(Keys.D))
    {
        //Add (not set) the time since last update. Also you update many times per
        //second. Because of this you need a much higher resolution if you don't want
        //to use a `TimeSpan` at least use milliseconds.
        MiningElapsed.add(gameTime.ElapsedGameTime);

        if (MiningElapsed.Seconds >= MiningEff)
        {
            BlockMined = true;
            MineReset = false;

            MiningElapsed = TimeSpan.Zero;
        }
    } else {
        //You have to reset the elapsed time or else when you stop and restart
        //mining it will already be partially completed.
        MiningElapsed = TimeSpan.Zero;
    }

```

P.S. I agree with Hackworth it is better to use a HP approach.

---
Tags: xna, c#, timer
---


title: How to simulate wind in 2D

text:
# Question
Title: How to simulate wind in 2D
For a 2D scenario, I want to have a fan blow at an object and make the object move with the "wind". How can I simulate the wind force blown by the fan?

# Answer
> 7 votes
Create an invisible box in front of the fan. Then check if some object is inside that box. Apply movement to that object.

This can be done in unity quite easily.

1. Create Empty gameobject
2. Select the new gameobject
3. Add Component-\> Mesh -\> Mesh filter
4. Select from inspector -\> Mesh filter -\> mesh and set it to "cube" ( or what ever shape you want )
5. Add Component -\> Physics -\> Box collider
6. Select from inspector -\> Box collider -\> Is Trigger to true ( checked )

Now, you have set up an collision trigger, that can detect if some object comes inside of it. Next, apply some force to push that object back or move it with translate directly.

Create new script to just created gameobject. Add inside that script these:

```
void OnTriggerEnter(Collider other)
{
     Debug.log("Object entered trigger");
}
void OnTriggerStay(Collider other)
{
     Debug.log("Object is in trigger");
     // Here you add negative forces to object that is within the fan area
     // Other is the object, that should be pushed away
     Vector3 position = transform.position;
     Vector3 targetPosition = other.position;
     Vector3 direction = targetPosition - position;
     direction.Normalize();
     int moveSpeed = 10;
     other.position += direction * moveSpeed * Time.deltaTime;

}
void OnTriggerExit(Collider other)
{
     Debug.log("Object left the trigger");
}

```

That should do it or atleast set you on right direction. This was written in late hours, it's not tested, but should work. Let me know if this was not what you wanted.

# Answer
> 0 votes
This is my way for achieving this effect:

```
void OnTriggerStay2D(Collider2D other)
{
    Debug.Log("Object is in trigger");
    player.rigidbody2D.AddForce (-Vector2.right*20000*Time.deltaTime);

}

```

---
Tags: 2d, unity, collision-detection
---


title: White background on BitMapFont

text:
# Question
Title: White background on BitMapFont
I've tried placing a white "background" on a font that is being rendered with LibGDX, with no success.

I'm using the `font.draw` to draw the loaded font on the screen, but every way that I tried, the font only contains a black border and is transparent on "the inside".

I'm using Hiero to make the `.fnt` from `.ttf` files that libGDX uses to render the fonts. Is there anyway I should modify from this application to make a font have a white background and not be transparent?

I would like to display the font the second way, although that display that you are seeing is just from the Hiero app preview option (with specific background).

# Answer
> 1 votes
Had a similar problem. Couldnt find anywhere the solution, only in libgdx irc channel. Huge thanks to jeffol on #libgdx @ freenode

So to change text colors the text outputted from Hiero (i used BMFont) should be white. This is done in export settings - you need to set higher bit depth, and then you can tinker with r g b values. What worked for me was the "outlined text with alpha" preset. Note that you set the outline not by drawing it into your font file, but in the font settings in BMFont.

Because this problem was bugging me so long, i actually quit several times while looking for a solution, i made a guide to solve this.

Here are the steps:

1)Take some font, note the outline thickness. The bigger you set the font size the more the outline thickness you should set.

2) Bit depth 32, preset - outline text with alpha. The settings become like this:

3) Press V to preview font, should look similar to this.

4) My code:

Assets class:

```
private static AssetManager asm = new AssetManager();
private static String fontPath = "font.fnt";

```

load() that is called at app startup:

```
asm.load(fontPath, BitmapFont.class);
asm.finishLoading();
font = asm.get(fontPath);

```

initialization:

```
font = Assets.font;
font.setColor(1f, 1f, 1f, 1f); //you can probably also use (Color.WHITE)

```

render:

```
font.draw(batch, score, camera.position.x-font.getBounds(score).width/2, 730);
//the x coord is adjusted depending on the text length,
//so for example the text is centered always

```

5) font in game works! :)

---
Tags: libgdx
---


# Question
Title: How can I perform a masked erase in SDL2?
I'm trying to implement some shadow/lighting effects in my 2D-project, and I've concluded that if there is an easy way to perform a masked erase on an SDL\_Texture, it would make the drawing operations quite cheap.

* Let's say I have a texture of the part of the level where light is not meant to be rendered.
* I also have a texture with my "light map"; I want to use this to just draw omni lights from my light sources.
* Then I want to use the first image to 'subtract' the portions of the light map that are not to be rendered on the final scene.
* Then I draw my "light map" texture on top of my scene, with additive blending enabled.

This sounds like a good theory in my head, but I can't see any functions in the SDL2 API that let me do masked erase from a texture.

Am I overlooking something? Does anything like this exist?

# Answer
I know its kind of old question but I see you got no answers and maybe its still relevant...

why do you want to use additive blending instead of modulate blending (SDL\_BLENDMODE\_MOD)? with modulate the output is dstRGB = srcRGB * dstRGB, so you can make your lit areas brighter (while white is maximum lit) and dark areas are the shade. if I understood you correctly the result would be exactly what you are trying to achieve.

if you are using a static lightmap its very easy, its just rendering a black & white texture over your scene with MOD blending. you can even use other colors to create colored lights.

if you want to be able to render lights dynamically on your light map you need to create an empty texture and fill it with black pixels, and then render "lights" on it with additive blending (meaning every light will only make the output brighter), where "lights" are simply textures that look like the light you want to add. something like this one:

then after you render all the lights render your texture over your entire scene with modulate blending. whenever you want to update the lighting map clear the texture to black again and redraw all the lights again.

to render on textures you should look into SDL\_SetRenderTarget. note that you will also need to create the texture with SDL\_TEXTUREACCESS\_TARGET flag and when you create the renderer add the SDL\_RENDERER\_TARGETTEXTURE flag.

if you are intrested I've written a graphic engine using SDL which has the lighting effect I described and the result looks like this: http://www.ness-engine.com/#!Tanks-game-demo-with-ness-engine/zoom/c9oo/image3e6

you can explore the source here, but its a lot of code..: https://github.com/RonenNess/ness-engine/tree/master/source/NessEngine
> 3 votes

---
Tags: sdl, lighting
---


# Question
Title: Slopes vs. Rectangles: Different Collision Points
My platformer has both rectangular tiles and right-triangle slopes with rectangular hitboxes. My sprites are also rectangular.

Collision with only rectangular tiles works well. Even if there are multiple rectangular tiles, collision still works pretty well.

Sprites can collide with individual slopes correctly as well, however, they collide at a different point. In order for the character's feet to be walking down the slope instead of hovering over it, the collision point for slopes is the bottom-center point. For rectangles, it is either corner.

The problem is moving from a rectangular tile onto a sloped one. The sprite resolves by the corners first, since it is resting atop a rectangular tile. However, the center point is resting above the slope, and the sprite will not move onto the slope until it is entirely moved off of the rectangular tile.

Here's a diagram:

How can I reliably use two different collision points for different tiles in a way that allows sprites to walk between rectangular and sloped tiles?

# Answer
Consistency is crucial for smooth collision detection. I recommend using the bottom center point for rectangular collision as well as slope collision when colliding against the ground.

For colliding against walls, you can use points that are in the center left and center right of your sprite.

Another way to think of it is as though your sprite has a diamond collision shape (i.e., a square rotated 45 degrees).
> 1 votes

# Answer
Your problem statement is not consistent...

You say you don't want rectangle corners to cross, so you have check collisions by corners.

But when there's a slope, you want your guy to descend the slope, and let rectangle corners cross. The "desired position" rectangle shows this crossing.

A solution is to keep checking the corners, and have your collision shapes not necessarily match your drawing shapes. Draw your slope beginning further to the right of the collision slope.
> 0 votes

---
Tags: collision-detection, platformer, aabb, separating-axis-theorem
---


title: Determining if a Point3D passed another

text:
# Question
Title: Determining if a Point3D passed another
I have 2 points `A` and `B` in 3D space (say of type Point3D). `B` needs to travel towards `A` and then stop either when it reached or passed `B`. The direction between the two points is known (can be easily calculated), so velocity is easy to set. How do I determine when point `A` reached or "passed" (given the direction) point `B`?

# Answer
> 2 votes
The vector between A and B is B - A. The magnitude of this vector is the distance between these points. If point A is traveling along this vector then it has reached point B when the magnitude is 0 and it passes B when the vector components change signs (positive to negative, or negative to positive) as compared to the original B - A vector.

For example, in 2D A = (3,4) B = (4, 6) B-A = (1, 2)

Point A will have passed point B when the signs of the vector components of B - A have changed compare to the original B - A values.

Another solution would be to use the dot product of the original B - A vector and the current B - A vector. If the value is positive then A has not reached B yet. If the solution is 0, then A = B. If the solution is negative then A has passed B. Further, if you normalize these vectors before you take the dot product you will get either 1, 0, or -1.

If A is not traveling along this vector then there needs to be a plane that contains B that acts as the threshold. A will start on one side of this plane and when it passes to the other side of the plane it would be considered passed B. Beyond that there orientation would be completely arbitrary.

---
Tags: mathematics, vector
---


# Question
Title: Can't seem to get Sprite to face left in sfml c++
I am having some small issues getting my sprite character to flip around. Basically I have a character that can walk to the right.. I am looking to flip it so that it looks like it is walking left. I haven't found a working solution at the moment so any help would be amazaing!

I am using:

SFML 2.1 C++

I have tried:

```
  guy.setTextureRect(sf::IntRect(guy.getGlobalBounds().width, 0, guy.getGlobalBounds.width * -1, guy.getGlobalBounds.height));

```

# Answer
> 1 votes
The `sf::IntRect` that you will use will be the same for both directions. What will need to be changed is the scale of the `sf::Sprite` variable.

You will simply need to do something similar to this:

```
// Assumes that the image side is 24x32 and it is the first frame of the sprite
sf::IntRect test(0,0,24,32);
playerSprite.setTextureRect(test);
if( walkingleft ){
    playerSprite.setScale(-1.0f,1.0f);  //flip the sprite
}
// draw sprite afterwards...

```

Is the code you tried on your question the exact code you tried out, because it looks incorrect?

guy.setTextureRect(sf::IntRect(guy.getGlobalBounds().width, 0, **guy.getGlobalBounds.width** * -1, **guy.getGlobalBounds.height**));

They are suppose to be functions.

---
Tags: c++, sprites, rotation, sfml
---


title: IBO interfering with VBO data?

text:
# Question
Title: IBO interfering with VBO data?
I have a vertex and color VBO that render a plane (2 triangles) just fine. However, when I attempt to use an IBO to render the plane, the vertices are completely off. My nice square looks all crumpled up...

I have experience in the past where an incorrect setting on the `size` parameter for `glVertexAttribPointer` skews ALL of the buffered data - color and vertex. It looks as if the IBO is doing the same thing somehow.

My code:

```
float[] colors = {    1.0f, 0.0f, 0.0f,
      0.0f, 1.0f, 0.0f,
       0.0f, 0.0f, 1.0f,
       5.0f, 0.0f, 0.0f};

float[] dataBuffer = {-1,-1,1,
      1,-1, 1,
      1,1,1,
      -1,1,1};

int[] idxBuffer = {1,2,3,3,4,1};

//**** INIT ROUTINE *****
  vboHandles = new int[3];
  gl.glGenBuffers(3, vboHandles, 0);

  //populate the position buffer
  FloatBuffer fbData = Buffers.newDirectFloatBuffer(dataBuffer);
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[0]); //the vertex data
  gl.glBufferData(GL4.GL_ARRAY_BUFFER, fbData.capacity() * 4,
          fbData, GL4.GL_STATIC_DRAW);

  //populate the color buffer
  FloatBuffer fbColors = Buffers.newDirectFloatBuffer(colors);
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[1]);
  gl.glBufferData(GL4.GL_ARRAY_BUFFER, fbColors.capacity() * (Float.SIZE / Byte.SIZE),
          fbColors, GL4.GL_STATIC_DRAW);

//index buffer IBO Vertex
  IntBuffer dtaIndc = Buffers.newDirectIntBuffer(idxBuffer);
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);
  gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, dtaIndc.capacity() * (Integer.SIZE / Byte.SIZE),
          dtaIndc, GL4.GL_STATIC_DRAW);

  //set vertex array index
  IntBuffer intBuffer = BufferUtil.newIntBuffer(1);
  gl.glGenVertexArrays(1, intBuffer);
  iVao = intBuffer.get(0);
  gl.glBindVertexArray(iVao);

  gl.glEnableVertexAttribArray(0);
  gl.glEnableVertexAttribArray(1);

  // Select the VBO, GPU memory data, to use for colors
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glVertexAttribPointer(0, 3, GL4.GL_FLOAT, false, 0, 0);

  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  // Associate Vertex attribute 1 with the last bound VBO
  gl.glVertexAttribPointer(1,3,GL4.GL_FLOAT, false,  0, 0 );

  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);
  gl.glVertexAttribPointer(2, 1, GL4.GL_INT, false, 0, 0);

//***************The render routine*****************
gl.glBindVertexArray(iVao);
//works great when I skip IBO and just use glDrawArrays
//gl.glDrawArrays(GL4.GL_TRIANGLES, 0, 6);

//vertices are all wrong when I use glDrawElements....
gl.glDrawElements(
       GL4.GL_TRIANGLES,      // mode
       idxBuffer.length,    // count
       GL4.GL_UNSIGNED_INT,   // type
       0           // element array buffer offset
);

```

Does anyone have any suggestion as to how I might resolve this? Obviously I'm thinking the IBO is offsetting the vertex data somehow but I don't know how I'd resolve that. Tried calling `glGenBuffers` separately for vertex, color and index but made no difference. Tried using Float for index (grasping I know...) just to keep the data types the same but threw an exception. I was also wondering if it is incorrect to use `glVertexAttribPointer` to associate the bound IBO? Is there a different function for that perhaps?

EDIT:

Without these two lines:

```
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);
gl.glVertexAttribPointer(2, 1, GL4.GL_INT, false, 0, 0);

```

I get the following error:

> A fatal error has been detected by the Java Runtime Environment:
>
> EXCEPTION\_ACCESS\_VIOLATION (0xc0000005) at pc=0x000000005ca0e6c0, pid=5196, tid=5112
>
> JRE version: 6.0\_21-b07 Java VM: Java HotSpot(TM) 64-Bit Server VM (17.0-b17 mixed mode windows-amd64 ) Problematic frame: C \[nvoglv64.DLL+0xb7e6c0\]
>
> An error report file with more information is saved as: C:\\&&&&&&&&&&&&&&&&&&\hs\_err\_pid5196.log
>
> If you would like to submit a bug report, please visit:
> http://java.sun.com/webapps/bugreport/crash.jsp The crash happened outside the Java Virtual Machine in native code. See problematic frame for where to report the bug.

I accept that the call to `glVertexAttribPointer` is incorrect as it obviously messes up the buffer and simply masks the above error. Could this error be caused by my index buffer being of type int and the drawelements requires uint?

# Answer
> 3 votes
You don't need to call `glVertexAttribPointer` for the indexes; the indexes are found from the bound `GL_ELEMENT_ARRAY_BUFFER` during the `drawElements` call (which is saved in the VAO state IIRC).

However indexes start from `0` so the contents of your index buffer are flawed they should be: `{0,1,2,2,3,0}`

---
Tags: opengl, java, vbo
---


title: Issues with ECS performance

text:
# Question
Title: Issues with ECS performance
I'm currently implementing ECS in "classic" sense, as defined by this wonderful post, where we have Entities, Components and Systems. And I'm having a serious (for me) performance issues. They come from the fact that System may need access to several components of the entity:

```
IList<int> es = _ecsManager.GetComponentEntities(ComponentType.RENDER);

int cacheRender = -1;
int cacheMovement = -1;
foreach (var entityId in es) {
    var rc = _ecsManager.GetEntityComponent<RenderComponent>(entityId, ComponentType.RENDER, ref cacheRender);
    var mc = _ecsManager.GetEntityComponent<MovementComponent>(entityId, ComponentType.MOVEMENT, ref cacheMovement);
    rc.Sprite.Position = mc.Position;
    QueueSprite(rc.Sprite);
}

```

the `QueueSprite` is my sprite batching, it's backed by regular arrays and `List`s with no dynamic in long run. And `GetEntityComponent` is:

```
public T GetEntityComponent<T>(int entityId, int componentId, ref int idxCache) where T : PslComponent {
    var cs = GetEntityComponents(entityId);
    // try for cache
    if (idxCache != CACHE_NULL && idxCache < cs.Count) {
        var tmp = cs[idxCache];
        if (tmp.TypeId == componentId) {
            return (T)tmp;
        }
        // cache miss
        idxCache = CACHE_NULL;
    }
    // cache failed, sequental search
    for (var i = 0; i < cs.Count; i++) {
        var component = cs[i];
        if (component.TypeId == componentId) {
            // update cache
            idxCache = i;
            return (T)component;
        }
    }
    // not found
    return null;
}

```

and `GetEntityComponents`:

```
public IList<PslComponent> GetEntityComponents(int entityId) {
    return _componentsByEntity[entityId];
}

```

with `_componentsByEntity` being a array, `GetComponentEntities` works similarly backed by regular array too:

```
public IList<int> GetComponentEntities(int componentId) {
    return _entitiesByComponent[componentId];
}

```

the abovementioned `foreach` loop is taking a lot of time. More than rendering.

As you can see, I'm pretty much tried to optimize a lot of things already, removing all `Dictonary<>`-type lookups, replacing all by arrays and `List`s. There is no dynamic allocation in long-run. The only problem, as I see it, is sequental search in entity Component loookup.

1. Is there any possibility to improve component lookup speed, while remaining true to classic implementation?
2. Is this major performance penalty is usually assumed then ECS is used? Are ECS "bad" then high performance is required?

# Answer
You could store components two-dimensionally in a list of lists:

```
List<List<PslComponent>> _componentsByType;

```

You use the component type ID as the index into the outer list...

```
List<PslComponent> componentByEntity = _componentsByType[componentTypeId];

```

...and then use the entity ID to look up the component of that type on that entity (or null if the entity does not have that type of component.

```
PslComponent component = componentByEntity[entityId];

```

You can lazily create the inner lists of components when you add a component of a particular type to an entity for the first time (when `_componentsByType[componentTypeId] == null`). Also, instead of using `List`, you could create a special kind of array backed list that allows you to set a value at any index in it by automatically growing the backing array to be big enough when setting.
> 2 votes

# Answer
To answer your question simply:

1. Get list of all the RenderComponents, and a list of all the Movement Components. We assume each component has a field which gives the entity is is a part of.
2. Sort them by entity ID. Obviously, if you keep these lists sorted in the systems themselves, then this is very inexpensive (maintaining the sorting is cheap).
3. Initialize an index of 0 into each sorted list. These indices will point to components.
4. If the two pointed to components have the same entity ID, then process them, and increment **both** indices.
5. If the two indices are different, then increment the index which points to the component with a **smaller** entity ID.
6. If either index points off the end of it's array after incrementing, you are done. Otherwise, goto 4. Note at *least* one index is incremented every iteration.

Why does this work? Essentially, everything before the two indices have already been processed, which includes entities with only one of the two components. We can never miss a pair because when the pointer reaches a certain component in the array, we know that it cannot move to the next component until the other pointer is at the same or a higher entity index. This mean that either we process the pair, or that the entity did not have a corresponding component of the other type. Symmetric reasoning from the other array means we won't miss any pairs there either.

This procedure is about as efficient as you can get. Further, if you pack the components themselves (not just the references) in sorted order, then it is extremely cache friendly. It can also be extended to more than two components, but that is slightly trickier.

This algorithm is exactly order O(n+m), where n and m are the counts of components in each list, but excluding the cost of sorting.

All we need from the ECS manager is the ability to get an iterable of the sorted components of a system. That's a pretty minimal interface. Looking up arbitrary components is important for interactions between entities, but in this case is not necessary.

Vectors/arrays are not magical, switching from a dictionary was a poor idea in this case, without realizing the above algorithm. O(1) lookup is useless if you use it to implement O(n) search.
> 2 votes

# Answer
Don't iterate over all entities and see if they have an interesting components - only iterate over entities that have your interesting component attached.

One way is to use a nested dictionary of the following type (no particular language here):

```
components: Dictionary<TypeIdentifier, Dictionary<Int, Component>>

```

This lets you look up the Entity -\> Component mapping in O(1) time.

TypeIdentifier is some kind of metatype's hashable identifier that is provided at compile time based on the class in which you are interested (Swift: ObjectIdentifier - C++: type\_index)

Entities are just integers (in my mind).

The Component would be some sort of abstract base class or interface/protocol type which you can statically cast to the more specific Position type – this is safe because you know for certain what type it will be based on the first layer of the dictionary.

Lots of languages have some notion of a hashable type id (C++ has type\_index, Swift has ObjectIdentifier, Python has classes, etc.).

For example, in Swift, I might do something like the following:

```
class Component {}

class Position : Component {
    var x: Int
    var y: Int
    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
}

typealias Entity = Int
var components = [ObjectIdentifier : [Entity : Component]]

for (entity, component) in components[ObjectIdentifier(Position.self)] {
    let position = component as Position
    println("Entity \(entity) has x: \(position.x), y: \(position.y)")
}

```

In C++, I might do something similar to this for the nested dictionary type:

```
std::unordered_map<std::type_index, std::unordered_map<int, std::shared_ptr<Component>>

```

or something like that.

At runtime, I can attach a Position component dynamically by just setting (abstractly speaking, without regard to a particular language):

```
components[Position][entity] = position

```

Later, if I key in with components\[Position\], I'll get another dictionary whose keys are only the entities that have a position. No side cache needed.

It's not without its problems, hashing isn't free, but give it a try. It'll limit the search space quite a bit if you have a lot of entities.
> 0 votes

---
Tags: c#, performance, entity-system
---


title: Fixed joints in 3D

text:
# Question
Title: Fixed joints in 3D
I'd like to build something like rigid origami in 3D space. So I need some mesh where each vertex is a particle and the set of the edges makes a chains/fabric where each edge is a "fixed length" spring and can drag the linked vertices.

I have no big experience with such a physical simulation, I have just made some experiments with verlet physics and the typical "cloth simulation". This is nice but each edge is deformed, streched or shrunken. And this is not good when you talk about rigid origami simulation.

Is there a way to make the verlet physics spring as a fixed length edges? Or maybe some different simulation engine I don't know? Inverse kinematic? Something else? I've seen in this question that Box2D can handle fixed length joints but it is in 2D only.

I'm not asking for a language-specific problem but just for information I'm using Java, OpenGL (JOGL), and toxiclibs.

# Answer
> 1 votes
Creating a such origami simulation is very complicated. In my opinion, to manage to create a such simulation, strong knowledge of geometry and math in general is required.

I would advise you to try to approach to this problem from the side of geometry rather than from physics side, because it is totally geometric problem. Adding physics to it (at least at first stages) would cause only problems.

I understand, that there is a temptation to just create a physically correct rectangle of paper like body, and physics engine will handle everything somehow. However this way would require a complex physics simulation. I do not know any game physics engines, that could do that. It would require a dynamic mesh generation, complex self collision handling, simulation of thing deformable plate, etc.

As for your original question about fixed length edges. If edges would be fixed length and rigid, the problem became more about kinematic, in other words - geometric problem.

---
Tags: 3d, physics, simulations
---


# Question
Title: What exactly does Unreal Engine 4's Class Wizard do?
I know "it adds classes to your project" and "creates boiler plate code for you" but what does that actually mean? Does it do anything besides properly generate your `.h` and `.cpp` files for you?

# Answer
I've never used UE4 but I've used UE3.

And yes by reading at the documentation, I believe it indeed does *more* than setting up two files with boilerplate code. Quotation:

> This converts a content-only project into a code project.

That should mean:

* Creating a Visual Studio or Xcode solution for the generation of user DLLs,
* Preparing it for compilation (c.f. this page),
* Maybe some messing up with the Unreal game project and its packaging, as the game will now run those custom DLLs instead (on top?) of the stock ones.

Probably more, but you get the idea.
> 0 votes

# Answer
It adds 'boiler plate' code to your project, based on what have you choosen. By doing this you are converting your content-only project to code project and that means that you can build it from Visual Studio/Xcode, and it will also slow down the building process. You can use the classes you have written in C++ in Blueprints, too.
> 0 votes

---
Tags: unreal
---


# Question
Title: How to share values between different shader programs?
I am using Unity but this might concerns all type of shaders. I would like to know if this is possible to share values between different shader pass.
Let's imagine that I am computing something in the first pass and I would like to use this value in a second pass, is it possible ?

If this is possible, how can I do that ?

# Answer
Absolutely, But not as simple as taking a return value of a normal function.

First I assume your question isn't about sharing variables between two shader stages (vertex, fragment..etc) but actually between two shader (programs).

Shaders are part of the rendering pipeline, every input/output should pass through the rendering pipeline and its memory is allocated on the GPU.

Regardless of each APIs terminology, you need to write to an intermediate buffer and pass that buffer to the next shader program. A widely used technique is to render to a texture and pass the texture into the next shader. Most of the advanced effects are implemented using a variation of this technique most; notably all of the deferred renders use this to generate of what is called a G-Buffer that contains several info about the geometry in the scene (Position, Normals, Tangents) all those are output of the geometry pass of the deffered render and encoded in buffer.

This G-Buffer is read by the deffered lighting stage, where all the values are read from the G-Buffer to perform what ever lighting calculations you need to perform. Other notable effects include reflections, where geometry is rendered for an offscreen buffer, and then assigned as texture with usually generated texCoords on the reflectors.
> 5 votes

---
Tags: opengl, unity, shaders, directx, glsl
---


# Question
Title: 3D Translations relative to 3D Rotations
I'm trying to program camera movement to be relative to camera rotation. (Forward is always forward, regardless of pitch, yaw, and roll) I want to be able to move forward, backward, left, right, up, and down.

**I do not want to use a matrix.**

**I want to use sin and cos from the standard math library.**

The camera rotates on all 3 axis. The rotation order is z(roll), y(pitch), x(yaw). When all rotations are 0, positive z is forward, positive y is down, and positive x is left.

So far I've gotten forward and backward movement to work with:

```
velZ = speed * cos(rotX) * cos(rotY);
velY = speed * sin(rotY);
velX = speed * sin(-rotX) * cos(rotY);

```

If somebody knows how to do this or knows where I can find information on this, it would be greatly appreciated.

# Answer
> 1 votes
In neutral position you have defined forward to be the positive Z vector (0, 0, 1). There are two vectors perpendicular to that vector (if we ignore sign), up (0, 1, 0) and left (1, 0, 0).

The easiest thing would be to create all three vectors and to apply a matrix transformation to find the left, up, and forward vector in 'camera space'.

```
Matrix transform = Matrix.CreateFromYawPitchRoll(y, p r);
Vector3 forward = Vector3.Transform(transform, new Vector3(0, 0, 1));
Vector3 left = Vector3.Transform(transform, new Vector3(1, 0, 0));
Vector3 up = Vector3.Transform(transform, new Vector3(0, 1, 0));

```

You do not necessarily need a matrix. You can also find the left and up matrix by using the cross product. (See here Unity's documentation on it, but the mathematical principals apply in general).

Once you have all three vectors you can strafe and move up by simply adding the correct vector (multiplied by movement speed) to the camera position (and look at) vector(s). For example:

```
public void MoveLeft(float speed)
{
    camera.Position = camera.Position + (left * speed);
}

```

---
Tags: mathematics, camera, rotation, movement, vector
---


# Question
Title: Unity yield WaitForSeconds() not working
I am new to Unity development. I started learning Unity by reading tutorials, demos, examples, and watching videos. And I am having some trouble with using this timer. Here is my code:

```
 void OnCollisionEnter(Collision colli){

    if (colli.collider.name == "Car") {
        Debug.Log("On Collision naz ~.~");
        Destroy(Car);
        Destroy(this.gameObject);
        GameObject clone = (GameObject) Instantiate(Bum, transform.position, Quaternion.identity);
        StartCoroutine(deleteObject(clone));
        // Just want to delete "clone" object after 1 second
    }
}
    IEnumerator deleteObject(GameObject bum){
        Debug.Log("chuan bi destroy naz ~.~"); // <-- run normally
        yield return new  WaitForSeconds(1.0F);
        Debug.Log("Destroy rui naz =,='");    //  <-- not display
        Destroy (bum);
    }

```

Why won't this object be destroyed after 1 second?

# Answer
> 1 votes
It's because you're going Destroy(this.gameObject) before starting the coroutine. A destroyed object cannot keep running a coroutine.

A solution would be to run the coroutine on the clone object.

# Answer
> 1 votes
You're destroying the object that contains the coroutine.

A simple fix for this situation is to use the extended version of `Destroy`.

```
// Destroy the bum after 1 second
   Destroy (bum, 1);

```

---
Tags: unity, timer
---


title: Proper way to encapsulate components?

text:
# Question
Title: Proper way to encapsulate components?
I've tried my hand at writing component systems and entity systems.

What I haven't managed to solve is the problem of event collision.

Say, we have an components A,B and C. A triggers 'kill B' event. When B recieves it, it erases the message (doesn't propagate it further). When C recieves it, it erases B. The order of which component will get the event first is not defined.

When the order is 'A,B,C', B stays alive but with 'A,C,B' B is erased. In other words, side effects of the event are undefined. A,B and C need to know about each other (which I don't want) to handle the event properly.

I intend to use components for games so for a more substantial example: we have an arrow (Projectile component) which fires of a collision event upon striking Link (Collidable component). Link has shield (also Collidable) which stops damage from affecting Link's Health component.

Arrows and health were written without the shield in mind and my component architecture is supposed to be encapsulated, so Health processes the collision event without knowing about the arrow or shield. Whether or not the damage is stopped depends on the order of components, which is random.

The best I've came up with is keeping a 'cache' of actions the event will do at the end of processing but still this solution has the same problems, only delayed. I could ditch events and try entity component system with storing 'mutations' in systems but that's not much different from just using global data for everything.

EDIT:

Okay, my communication skills are terrible. Here's what I've done to make components working without knowing about each other:

1. Use 'pure' entity system (components are pure data, all logic in systems)
2. Components do not talk to each other. The systems talk to each other by adding system-exclusive components to entities
3. Systems for above situation are: Movement, HandleCollision, ApplyArrowDamage. Movemen t appends a Collision component to the 'reciever' of the collision (Link) when calculating movements. HandleCollision reacts to Collision component, appends ArrowDamage component to Link entity and removes Collision component from Link. ApplyArrowDamage does just that and removes ArrowDamage component and maybe appends Dead component to be handled elswere.
4. Now, to create the situation when the shield blocks arrows, I create an CheckShield system and place it between HandleCollision and ApplyArrowDamage. CheckShield works with ApplyArrowDamage, checks whenether the reciever (Link in this case) has a shield equiped and removes ArrowDamage component if so.
5. This way, my old code doesn't need to account for new code to work properly and vice versa.

For the 'ABC' situation I do the same: If I want C to erase B, I write a new system that works with C and fires off before the system that works with B. The only sane way to solve this problems with event raising is to keep rethrowing the event whenether it's state changed, and keep rethrowing it until it doesn't changed in the last iteration.

# Answer
You're possibly trying to over-use game object components.

The shield doesn't need to be a component. It's an equipped item. That might be handled entirely by the `InventoryComponent` (it doesn't have to be, but it's an option).

So far as damage, yet another option is to make sure that the `HitPointComponent` is aware of the states and things that alter damage taken and does the adjustment internally. This might be by querying the `InventoryComponent`.

Another option is for the shield to create a separate collision box in front of the character. If that collision box is hit then it takes the `DamageMessage` in a `ShieldDamageReceiverComponent`, halves the amount, and forwards it on to the main character object. This also gives you direction-based blocking. Larger, more complex characters in 3D games will often use their physics models for this purpose without necessarily needing separate game objects.

One of the nice things about components is that you can just use different components in different circumstances. e.g., you don't need a single `HitPointComponent`; you can have a `HeroHitPointComponent` that takes into account shields and such, an `EnemyHitPointComponent` that does not, and so on. Just be careful of walking into a design where you need to mix-and-match those behaviors, but don't avoid the setup out of hand.

Remember, component-based design is a collection of patterns, not a single solution. You can have a game object like your character made up of "components." Your `ArmorComponent` can then be made up of a dynamic set of `ArmorModifier`. That's a component that has components, basically. It might not be implemented with an actual set of sub-objects, but the general idea is the same. Your `Engine` can be a composite of `Module` components. Your resource objects can be composites of resource providers. etc.
> 0 votes

# Answer
Consider using Sub/Pub pattern, or Observer pattern as a messaging system. This will allow you to register as many event listener as you want, while keeping all the listener decoupled. The basic idea is you keep a list of objects that want to get the message when an event happens. When the event does happen, you iterate through the list, sending the event message to every object registered to receive it. Each object will process the message however they need to. If a listener no longer needs to receive the message, you simply unregister it.
> 1 votes

# Answer
Event handling can be done using Observer pattern. What it does is that it forwards a certain event to the all registered objects. Let's say we have a projectile entity which triggers two events: OnThrown and OnHit. During or after the creation, components which want to listen that event registers it by passing a callback with a syntax like this:

```
projectile.registerOnHitEvent(handleProjectileHit);

```

Projectile component keeps all registered callbacks in an array so you can call them with a for loop.

```
private void fireOnHit()
{
    for(int i=0;i<hitCallbacks.length;i++)
    {
        hitCallbacks[i](this);
    }
}

```

In addition, you can decide whether the next callback will receive the event by checking the return value;

```
bool notifyOthers = hitCallbacks[i](this);
if(!notifyOthers)
    break;

```

As the further customization, you can assign priorities so that shield component will always receive the projectile hit event first and doesn't allow propagation.

Note: I would let damage handling to the character controller, so it can find out whether there is a shield or not.
> 0 votes

---
Tags: entity-component
---


# Question
Title: Why can't I create an unordered access view of a R32G32B32_UINT buffer?
So I'm trying to create an unordered access view for a buffer having with three component elements, but it fails with this warning:

```
D3D11 ERROR: ID3D11Device::CreateUnorderedAccessView:
The format (0x7, R32G32B32_UINT) cannot be used with a Typed Unordered Access View.
[ STATE_CREATION ERROR #2097343: CREATEUNORDEREDACCESSVIEW_INVALIDFORMAT].

```

This is my code:

```
void test(ID3D11Device* dev_ctx) {
  D3D11_BUFFER_DESC buff_desc;
  memset(&buff_desc, 0, sizeof(buff_desc));

  buff_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
  buff_desc.ByteWidth = 1024 * 12;
  buff_desc.CPUAccessFlags = 0;
  buff_desc.MiscFlags = 0;
  buff_desc.StructureByteStride = 12;
  buff_desc.Usage = D3D11_USAGE_DEFAULT;

  ID3D11Buffer* buff_ptr = nullptr;
  dev_ctx->CreateBuffer(&buff_desc, nullptr, &buff_ptr);

  if (!buff_ptr)
    return;

  D3D11_UNORDERED_ACCESS_VIEW_DESC uav_desc;
  uav_desc.Format = DXGI_FORMAT_R32G32B32_UINT;
  uav_desc.ViewDimension = D3D11_UAV_DIMENSION_BUFFER;
  uav_desc.Buffer.FirstElement = 0;
  uav_desc.Buffer.Flags = 0;
  uav_desc.Buffer.NumElements = 1024;

  ID3D11UnorderedAccessView* uav_ptr = nullptr;
  dev_ctx->CreateUnorderedAccessView(buff_ptr, &uav_desc, &uav_ptr);

  if (!uav_ptr)
    return;
  }

```

It fails for any resource with three components (`R32G32B32_*`), but it works if the resource has 1/2/4 components. So what could be the problem?

# Answer
> 3 votes
The problem is basically spelled out for you in the error message: Direct3D does not support the use of the `R32G32B32_UINT` format in a typed UAV. MSDN has a section on supported formats for typed UAVs. `R32G32B32_UINT` is not on the list.

---
Tags: directx11
---


title: Fast exact frustum culling for sphere

text:
# Question
Title: Fast exact frustum culling for sphere
Given a view frustum and a sphere, how do I exactly determine whether or not the sphere intersects the frustum? The typical way of checking a sphere against a frustum finds the signed distance of the sphere center from each frustum plane, but this isn't an exact test and will sometimes fail:

One method is to split the frustum geometry into triangles and test each triangle against the sphere for an intersection but this is slow.

Can SAT be used with a sphere? Are there any other faster methods?

# Answer
If the sphere center lies outside 1 of the planes, check for distance to plane. If it lies outside 2 of the planes, check for distance to the edge they form. If it lies outside three of the planes, check for distance to their shared intersection point.

If it's actually a sphere in pretransformed world space, you can intersect against the pretransformed rectangular prism and it's pretty easy. If you're really intersecting a sphere against a truncated pyramid frustum, then there's a little more math to work out, and some edge/corner cases (ha) to do with lying outside 3 faces that don't form a corner.
> 1 votes

---
Tags: frustum-culling
---


# Question
Title: How do I create a custom "Google Maps" visualisation from game map images?
I am attempting to create the equivalent of a Google Maps map for a private Ultima Online server, with a custom map replacing the default map.

I'd like to allow players to pin important locations on the map and post screenshots of their play activity at a particular location.

I've seen this done in other games like Wurm Online. Does such a version of Google Maps (or a similar service) exist? Or would I have to build it myself?

# Answer
There is http://openlayers.org/ which should provide exactly what you need.

As seen in the example on http://openlayers.org/en/v3.0.0/doc/quickstart.html it creates a scrollable map like google maps(but can do other types as well) and allows to place custom marker and overlays.

It does not help you with the map tile generation - it is only there to use map tiles and display them within the browser in a google-maps style.
> 1 votes

---
Tags: maps, web, visualization
---


# Question
Title: Rotating an object to point towards the mouse
I'm using slick2d for this process and trying to rotate a minigun to face the mouse. My problem is that the minigun in my game is actually rotating but no towards the mouse at all! Also, the minigun goes as far as 180 degrees and stops there.

Here is my minigun class that I have put inside another core class to be updated and rendered.

```
public class Minigun {

    private Animation Shoot;
    private SpriteSheet sheet;
    private int x = 200, y = 150;
    private double angleToTurn;
    private Input input;

    public Minigun(){
        try {
            sheet = new SpriteSheet(new Image("res/minigun.png"), 130, 34);
            Shoot= new Animation(sheet, 1, 0, 2, 0, true, 1, true);
            Shoot.setLooping(true);
            input = new Input(1);
        } catch (SlickException e) {
            e.printStackTrace();
        }

    }
    public void render(Graphics g){
        g.pushTransform();
        g.rotate(x + Shoot.getWidth() / 2 , y + Shoot.getHeight() /2,   (int) angleToTurn);
        Shoot.draw(x, y);
        g.popTransform();
    }
    public void update(){
        double mX = input.getMouseX();
        double mY = input.getMouseY();
        angleToTurn = Math.toDegrees(Math.atan2(mY - y, mX - x));
        System.out.println(angleToTurn);
    }
}

```

# Answer
> 1 votes
I figured out the problem myself! After printing the coordinates of the mouse to the console I realized that where just something missing with my Input. Sure enough, I added GameContainer to the constructor of minigun and set input to equal GameContainer.getInput();. It works perfectly now :D

```
public Minigun(GameContainer container){
        try {
            sheet = new SpriteSheet(new Image("res/minigun.png"), 130, 34);
            Shoot= new Animation(sheet, 1, 0, 2, 0, true, 1, true);
            Shoot.setLooping(true);
            input = new Input(1);
            input = container.getInput();
        } catch (SlickException e) {
            e.printStackTrace();
        }

```

---
Tags: java, slick, mouse
---


# Question
Title: I want to show total time spent by all players around the world in my game
I am developing a Unity3D game. I want to show in my game:

1. Total time spent playing all time by all players around the world
2. Total time spent playing in last 24 hours by all players around the world

I heard that it can be achieved by analytics services like Flurry / Google Analytics. I did some research but I am not getting anywhere by myself. Can anybody guide me to the right path?

# Answer
> -1 votes
The best option is to use a database to store your player data. What database to use is ultimately in your court and what seems relevant based on your own research.

Inputting that data into a database should be easy for these two metrics simply because you're only talking about tracking the login date and timestamps of your players. Those timestamps will have to be stored every time they log into the game and when they log out.

Then simply put, you could query your player log data to return a result to Unity that displays in game as the TSQL query example below:

```
SELECT
  [player-id]
  ,DATEDIFF(MINUTES,[log-on-time],[log-off-time]) AS [Time Difference]
FROM [DATABASE_NAME].[SCHEMA_NAME].[TABLE_NAME]
WHERE [player-id] = ...

```

Then this would result in the time difference between the log on time and log off time. Of course, if the user is currently playing, then you can alter the query to use GETDATE() functions depending on the RDBMS you are using to get the time difference between the log-on-time and the database server time for live players and ETC.

I would recommend this as opposed to trying to find a quick-fix or possibly licensing someone elses analytical reporting system. That's because you may find yourself wanting to store more data about your players that you also want to report on in-game as well out-of-game for your own personal metrics of the games progression.

# Answer
> 0 votes
You simply need a database. You store the login time and the logout time. You then simply compute and aggregate the time. This could be done continuously or whenever it is needed.

Another option that is easier to implement but a little bit more resource intensive is to have all players "fire" a http request every 10 seconds (or similar) to the server that creates a record in the database that signifies they have now been playing for 10 seconds straight. Then to sum up the amount of time that has been played you simply do a count on such records from the past day and sum up the total and multiply by 10 seconds. Older records could be aggregated and deleted from the database to free up space.

---
Tags: unity, databases, analytics
---


title: Move an object based on XML/TXT file

text:
# Question
Title: Move an object based on XML/TXT file
Let's think I have an file which looks like this:

```
0 1 2  3
4 5 6  7
8 9 10 11

```

I want to create a move from this file. For every 1s(mentioned in the file) I want to move the object.

Is this possible to do or there is already scripts/implementations which can be used?

Suppose I have an xml file which looks like this

```
<Box>
<Time>0.02</Time>
<Distance>0,7.889,0</Distance>
<Time>0.02</Time>
<Distance>0,7.885,0</Distance>
<Time>0.02</Time>
<Distance>0,7.887,0</Distance>
<Time>0.02</Time>
<Distance>0,7.885,0</Distance>
</Box>

```

I want to move the object based on the distance specified in the xml sheet.We have a timer running shown in GUI Text.At the time interval shown in the xml the object should move to the certain distance shown in the xml.How can I do this?Please help me out in hard coding this.

# Answer
In Unity you can load any text file with Resources.Load() like this:

```
string text = (Resources.Load("NameOfTextAsset") as TextAsset).text;

```

After that you can use any standard C# method to split the string to parts, and Convert.ToInt32() to parse the integer from the splitted up string.

```
foreach(string part in text.Split(' ')) {
    int number = Convert.ToInt32(part);
    Debug.Log("Number: " + number);
}

```

Read more about this very basic C# stuff:

http://docs.unity3d.com/Manual/class-TextAsset.html

http://docs.unity3d.com/ScriptReference/TextAsset.html

http://www.dotnetperls.com/split

http://msdn.microsoft.com/en-us/library/ms228388.aspx

http://msdn.microsoft.com/en-us/library/bb397679.aspx
> 2 votes

---
Tags: c#, unity
---


# Question
Title: using rperp or perp to find perpendicular of a vector
i have code local coordinate

```
Vec2 velo = Vec2(100,0);
Vec2 Heading = velo.getNormalized();
Vec2 side = Heading.perp();
Vec2 trans = Vec2(12,12);

```

then i can generate toWorldCoordinate for trans vector:

```
word.x = heading.x* trans.x + heading.y * trans.y + pos.x;
word.y = side.x* trans.x + side.y * trans.y + pos.y;

```

im trying to apply example from book: game ai by example, using cocos2dx. in cocos2dx we have rperp and perp for aplying perpendicular. and in my POV, cocos y is pointing up then we should use (-y,x) that is perp function.

but its seem the actor movement y is reversed then. im realy confused with concept right hand / left hand. **using rperp is fix the issue**. but im still not understand why rperp should be used? afaik to make y pointing up we should use perp (-y,x) which is (1,0).perp = (0,1);// the destination is upward

# Answer
> 0 votes
It is unclear as to why you are using a perpendicular. There isn't enough detail to describe the problem you are working. However, perhaps this will help.

A 2D vector can be described using the values (x, y). The left hand perpendicular and the right hand perpendicular are easily calculated.

The left hand perpendicular of (x, y) is (-y, x). The Right hand perpendicular of (x, y) is (y, -x).

This can be easily seen with an example. On a grid where positive y is up, and positive x is to the right, a normalized vector pointing up can be written as (0, 1).

The left hand perpendicular of (0, 1) is (-1, 0). The Right hand perpendicular of (0, 1) is (1, -0), or (1, 0).

---
Tags: mathematics, vector, cocos2d-x
---


# Question
Title: Is there any way to change compression type of TMX file?
Basically it's all in the title, you can choose compression type then you create new tile map, but after it's done the "Save As..." option doesn't provide compression type selection.

# Answer
> 6 votes
You can change it in the map properties. (Map -\> Properties...)

---
Tags: tiled
---


title: Monogame Windows Phone 8

text:
# Question
Title: Monogame Windows Phone 8
I want to port a WP7 XNA game to WP8 using MonoGame. The thing is that I have Windows 7. So here's the questions (if some sound dumb, please bare with me).

* Do I need to have Windows 8?
* Do I need to have the Windows Phone SDK 8?
* How do I get the templates for Visual Studio so I can create a project for WP8?

I'm kinda newbie into this monogame thingy. I've been using XNA for quite a while.

# Answer
> 1 votes
Yes, you need both Windows 8 and the Windows Phone SDK, a detailed tutorial describing how to setup up MonoGame for WP8 (written by a Microsoft Employee) can be found here

Edit: There is (supposedly) a way to install the Windows Phone SDK on Windows 7 ( described here ) but it is not officially supported by Microsoft and therefore not guaranteed to work.

---
Tags: xna, monogame, windows-phone-8
---


# Question
Title: How does making of games using game engines happen?
I am a complete beginner to game programming. I have decided to give a try on UDK game engine. I have some simple doubts. I searched Google for the answers but couldn't get my doubts cleared.

This is what I have understood about a game engine: They are used to reduce our workload by doing the jobs which are common in games. They abstract the complex level and give us a more easier layer to work with. So when using a game engine we can concentrate on our game logic and the engine will do those complex but common tasks. I understand that game engines are built over APIs like OpenGL.

Now the doubt comes: *How do we make OUR game from a game engine?* Does every game engine provide a API through which we can interact with it and get our game from it?

I thought of analogy. This may not be a real analogy. Suppose we are building a house. The engine provides as a skeleton of a house in which the common works like foundations and walls which are common to all houses are given. Now we want to put a window of our choice into the house skeleton. We interact Through the API and find the position or hole where we can put our window which was made externally. Does this analogy make sense??? Is UnrealScript The language used to use the API provided by UDK so that our "Window" can be inserted to the "House"?

# Answer
> 1 votes
### Extreme tl;dr

Your goal as a game developer is to provide assets and a script that describes mechanics specific to your game so the Engine can preform game logic and present game assets (rendering graphics and playing sounds an music) in the appropriate way. For this purpose there are tutorials, examples and books online. There are hundreds of useful articles on how to properly apply an Engine like Unreal to achieve common design goals. For something very specific, ask a specific question.

Think of an Engine as the things that "gets out of the way" and takes with it a bunch of responsibilities you don't want to handle; like repainting your house, cleaning the bathroom, cooking dinner, cleaning the mold in the refrigerator, fixing the broken plumbing, paying taxes, filling up your car's tank with gas before it runs out and things you take for granted like making sure the Sun lights upon this world so we don't all freeze to death and that rain pours in the winter to grow our corps. The Engine takes care of all the necessities common to most if *obviously* not truly all games.

I forgot to mention that engines often come with documentation, it is not explicitly demanded but implied that a good reliable Engine comes with tutorials and examples.

### tl;dr summation

So basically an Engine is a huge load of hard to implement services that require sometimes myriads of women and men hours to produce.

* It loads assets from the disk.
* It handles input from the user.
* It often understands the device and offers some existing cross-platform support and native features.
* It plays music and sounds.
* It renders the game entities into the view.
* It often handles physics.
* It may handle networking, connections with the server and peers.
* It may even offer easy, streamlined ways to create content like levels.
* It often comes with existing assets, sometimes free, levels, models, animations, texture and such which could be used as place holders or fill in for some of the art at least in the alpha stage.
* Well documented and well explained, popular Engines often are often taught in books, youtube videos, blogs and other resources online.

In other words, it does **everything** that is needed for the groundwork and does not decide the rules of your game and how things look and sound but it allows you to display those things, write those rules as a human readable & programmer friendly script and play those sounds and music. It will help you to enforce some common rules like physics and collision detection.

## Longish version ("this way there be dragons"):

---

Lets clarify (generalizing) what the Engine does for you and what you do yourself.

There are certain services, that each "house" in your metaphor or Game if we get down to it, needs. These could be electricity, water, gas and higher level services like cleaning, maintenance (paint and plumbing) and cable.

What does a game need?

1. It needs to display a compelling image on the screen! A game or two with a black screen exist but this is the most common kind.
    1. The images are often changing, so it needs to display things in motion. (the walls might not be moving but the camera is hence *in motion* and not necessarily *moving*). Now if we generalize it depends if the game is 2D or 3D.
        1. 2D - We need to place sprites on the screen, this is often called "Blitting" which is basically copying 2d image data from a sprite frame to the screen. There are also more modern ways than "Blitting" that use hardware accelaration, basically placing the sprite as a texture on flat rectangular planar object and using the GPU to render it.
            1. Some 2D games require (inbe)tweening which is a way of saying how the animation is paced for a game entity.
        2. 3D - We need to talk to the 3d api (like OpenGl or Direct3D) and render models (data representation of a 3 dimensional visible entity) in real-time (this is not easy to do).
            1. If it's 3D it includes, lighting, refraction and interpolating between frames of animation too among other things.

So an engine would probably provide services that render or Blit entities to create a compelling view of the happenings in the game. You wouldn't want to write a real time rendering or "Blitting" service if you simply wish to make a game.

You would want to say, `creature.position = (x, y) // display creature at (x, y)` and it looks like this image or that model.

2. Loading assets into memory. Like we said, the creature looks like an image, an animated sprite or a 3d animated shape. It is often a piece of art, an asset that was created by an artist in a tool suited for that purpose. This data needs to come from somewhere? It often comes from a design tool, like Blender / 3d studio Max for models or Paint.net (Too many 2d tool to list) for animated sprites. It is then saved on the disk in the some file format. Someone needs to load this asset into memory for it to be handed over to the rendering service.
    1. 2D - You need to load images and understand the image format.
    2. 3D - You need to load 3D textured animated models. Often times with bone animation.

So an engine needs to understand how read files; you don't want to write a file parser. The files are on the disk in some format and you simply want to say `Load 'fileName.ext'`and the Engine needs to convert that data into something useful that could be rendered by the rendering service. The rendering service wants the data parsed (digested) and explained in the way it understands it. If the files change, you don't want to have to replace the entire rendering service, that's right?

3. Common physics - often time Engines may provide physics simulation. This is very difficult to implement on your own. Collisions are also hard to detect in 3d space or in a pixel perfect way without compromising performance and most importantly getting it bug free, unless someone who does it well, sits and invests the time to get it right.
4. Cross platform support and networking anyone? So you written your game in some low level language. Does it support other platforms and do you have stable, bug free multiplayer? Probably not. Unless you used a library like SDL/SMFL.
5. Often left unnoticed, conventions (emphasized over configuration \[this is important in large teams but also for time pressed individuals\]), solutions for bike shed issues.
6. Support for multiple input devices like keyboards, mice, XBOX controllers and such.
7. Some Engines come with excellent tools to create assets like levels in your game. It may even have a large database for assets for sale or ones that are free to download.

I admittedly probably missed something or glossed over some subject but this covers most of what an Engine does for you.

So what is left for you the developer?

* Write the story of your game. What is the game about not only in a narrative way; in a gameplay experience way, what journey is the player going through, what challenges does she face on her path to triumph, puzzles, monsters and traps of doom?
* Write the rules and mechanics in the game, can the player jump in the air or maybe go through solid walls? What happens when the game character kicks a Hobgoblin in the face?
* Record sound and music for your game.
* Create attractive art assets that truly suit the theme and atmosphere of your game.
* Fine tune the controls to perfection.

To apply this in practice you need to understand the scripting language used with the Engine and build a code base that describes the rules and intended functionality of your game. Like I mentioned before, there are many tutorials and examples to get you started.

# Answer
> 1 votes
The engine is the underlying platform on which your game code sits. The purpose of the engine is to abstract the raw driver / dx / opengl API away from us and make it easier to work with.

It merely acts as a "toolkit" on which we build our games. Languages (such unrealscript) are simply part of that toolkit and enable us to do what we need.

Ok so for your many questions ...

> How do we make OUR game from a game engine?

We build our own logic on top of the engine API that does our "unique" game related stuff.

> Does every game engine provide a API through which we can interact with it and get our game from it?

Yes, to provide an API is essentially the part of the core purpose of a game engine.

> Does this analogy make sense?

Sort of, but the engine is much higher level than that ... It says "using this function you can draw stuff and define something you call a wall, in which you can also define something you can call a window and put that inside your wall".

Engines don't worry about things in the real world like "walls" they translate your definition of a wall as shape and material information in to API calls against directX or OpenGL.

> Is UnrealScript The language used to use the API provided by UDK so that our "Window" can be inserted to the "House"?

In the case of the unreal engine ... yes in a sense, "unrealscript" is a language unique to the "toolkit" that the engine provides to enable you as the developer to put games together.

Hopefully that solves your confusion?

---
Tags: udk
---


# Question
Title: Warcraft III, SharpCraft C# plugin: Usage of native "TimerStart"?
### about:

Blizzard Warcraft III \[furthermore abbreviated as **WC3**\]
*related version: WC3: The Frozen Throne 1.26.0.6401 (german Patch 1.26a)*
MindWorX Sharpcraft \[furthermore abbreviated as **SC**\]
*related version: 1.2.4.0*

### issue:

I'm trying to use the native "TimerStart" from the **WC3** "common.j" package inside a **SC** plugin written in C#. what gives me problems is the last argument from the native ("code handlerFunc"). as there is no native for creating functions, I dont know how to use it properly, can you give an example? for reference of the "code"-argument (it isnt even declared in the "common.j") i used Vexorians thread on wc3c.net, part: "I. The code type". here is the native like declared in "common.j":

```
native TimerStart           takes timer whichTimer, real timeout, boolean periodic, code handlerFunc returns nothing

```

in the **SC** plugin I initialized the native like this:

```
private delegate void TimerStartPrototype(JassTimer whichTimer, JassRealArg timeout, JassBoolean periodic, JassCode handlerFunc);
private static TimerStartPrototype TimerStart = WarcraftIII.Jass.GetNative("TimerStart").ToDelegate<TimerStartPrototype>();
//native TimerStart           takes timer whichTimer, real timeout, boolean periodic, code handlerFunc returns nothing

```

additionally in **SC** plugin, I created a void to pass to the last argument of the native: *(note that "StopCamera" is another native from "common.j" i also initialized in the **SC** plugin but not showing here, because it is done in the same way "TimerStart" was.)*

```
private delegate void StopCameraFuncPrototype();
private void StopCameraFunc() {
    StopCamera();
}

```

usage of the native "TimerStart" in **SC** plugin: *(note that the variable "jTim\_mouseWheel" is a "JassTimer" created somewhere else in the **SC** plugin.)*

```
TimerStart(jTim_mouseWheel, (JassRealArg)0.01, false, (JassCode)StopCameraFunc());

```

when im trying to run **WC3** with **SC**, the **SC** console window prints that it couldnt compile the appropriate plugin \*.cs-file due to not being able to convert void to JassCode. by simply renaming "void" into "JassCode" I get the error, that not all code paths return a value...

# Answer
The `JassCode` type is only there as a placeholder, and it doesn't have any actual use right now. The `code` type from JASS is a pointer to a function in a maps compiled JASS script.

I have tried creating new JASS script code at run-time, but I haven't had any good success so far.

Since you're using 1.2.4 there is really no way to achieve what you want. If you were to switch to 2.2.5.124b you'd be able to use the system for attaching C# delegates to a `JassTrigger` with the following code.

```
var trigger = JassTrigger.Create();
trigger.RegisterTimerEvent(0.01f, true);
trigger.AddAction(new DelegateAction((JassTrigger theTrigger) => {
    /* do stuff here */
}));

```
> 2 votes

---
Tags: modding
---


# Question
Title: Executing commands at the exact same time on 2 or more computers
I have an RTS game, with deterministic simulation, but if I want multiplayer to actually work, I need commands sent between computers to be executed at the exact same time. My game's networking is just sending commands between the players' computers, and the simulator executes the commands in order, which, hopefully, will result in each player seeing the exact same game. However, if the commands aren't executed at the EXACT same time, then the simulation will become out of step and everything will be wrong. How could I do this, and are there other ways to make sure everything is in sync?

# Answer
> 1 votes
There are two possible approaches to what you are describing, one wrong and the other useful.

1. The wrong approach is to simply delay the user input from activating the command. Assuming you know the other clients can be informed 99.9% of the time in half a second, delay the command for half a second and send it to the other clients as the pair `<command, activationTime>` so the other clients could all preform the command synchronously. Obviously, you have to sync the clocks when the processes start which is a question on it's own.
2. The correct approach would be to perform the command slightly later on other clients but have them behave programmatically as if the command occurred at an earlier time. i.e you time-step back some milliseconds into the past, preform the command and then re-evaluate the simulation from that point, preforming any other later command as necessary until the current time. This could lead to jittering (sudden changes in position). You can smooth these out by interpolating the animation between the true state and the subjective state on the client. i.e starting from `t * trueState + (1 - t) * subjectiveState` and increasing `t` by easing out and easing in.
3. Alternatively, you could abandon this approach completely and use one of the clietns as a Server and the others as "dumb terminals" that only accept input and display the current state of the game; this way instead of sending orders, you constantly send updates on the new positions of units, evaluating a few steps into the future for slower connections and a more accurate present state for faster (LAN) or low latency connections.

Doing the third approach is easier, there is only one simulation. Synchronizing two simulations would be very hard, to the point of impossible. It is an interesting academic experiment and perhaps could yield useful lessons but does not seem likely unless the gameplay is very insensitve to slight variations in timing which most real time games simply aren't.

This is an example of the graph for easing out and easing in when interpolating / tweening states:

---
Tags: networking, multiplayer, rts, messaging, realtime
---


# Question
Title: Quick algorithm to identify undrawn rectangles inside a map
I already have a working algorithm for this but it's home-made and there is some redundancy in the things it checks, so I'm looking for a fast algorithm (or the name of it) that would detect undrawn portions of a 2d map (a picture or a grid), returning those portions as a list of Rectangles **which borders are parallel to the axis** (x, y, width, height). The map is not very big, like 200x200.

Edit: **Rectangles to detect have to be parallel to the axis x and y**

For instance ran on this map and looking for space character " " and for 2x3 rectangles :

```
*C***DDD****
*01F  *E*  *
***   ***  *
**    *    *
*A****  ****
************

```

It would detect the portions marked with "X":

```
*C***DDD****
*01FXX*E*XX*
*** XX***XX*
**  XX*  XX*
*A****  ****
************

```

Has anyone heard of one algorithm like this, but fast? Right now what I'm doing is that I'm scanning through each cell and checking if the w\*h Rect at current position is filled with the search value. However you can see there is a lot of redundancy there.

I wonder if some bitmap compression algorithm like PNG don't use that kind of detection, so as to compress repetitions of tiles/uniform areas. If that's the case that should be very fast algorithm they use because speed is an issue for them.

The detection doesn't have to be exact (it's ok if some areas are not detected, but most need to be). So mostly it needs to be very fast.

# Answer
This algorithm will identify the lower right corner of every a by b block of non-blocked tiles.

We iterate over the rows of the grid from top to bottom, keeping an array as wide as the grid of integers as state. Initially this array is all zeros. Within a row, we proceed from left to right. Initially, a counter is zero at the beginning of every row. We look at the cells of the grid in order. If a cell is blocked, then we reset the count to zero. If it is unblocked, we increment the count. Thus after we have done this test the counter tells us how many open spaces (including the current one) it is until the next blocked cell.

After we have reset or incremented the counter, we compare it to the width a. If it is greater or equal, then we increment the counter for that cell in the array. Otherwise, we set that counter to zero. Essentially, if there is enough space in the current row at a given column to hold one row of our a by b rectangle to the column's left, then the array counter for that column is incremented. Thus, if the array counter at a particular place is at least b (the height of the sought rectangle), then there are b-many a by 1 rectangles above and including the current row, with their right edges in the current column. Therefore, after incrementing/resetting the array counter, if it is at least b then we have found the lower right corner of an a by b rectangle.

This algorithm has complexity O(m\*n), where m and n are the width and height of the grid. This is as efficient as possible, because any algorithm solving this problem must read every cell of input in the general case. In addition, this algorithm has a fast inner loop, and very cache friendly.
> 1 votes

# Answer
EDIT: Ok apparently this is totally different question now so here's my factored answer (v3) ...

Marching Squares

http://www.emanueleferonato.com/2013/03/01/using-marching-squares-algorithm-to-trace-the-contour-of-an-image/

Taking this approach will allow you to crawl your map and determine areas on the outside of / inside of something.

This assumes you can easily represent your map as an image and then "march" the pixels.
> 0 votes

---
Tags: algorithm, maps, spatial-partitioning
---


title: TileMap not not rendering

text:
# Question
Title: TileMap not not rendering
I have a tile map that I would like to be able to move while playing the game. In the code you will see the posX and posY variables. I used these variables so that when I complete this, I can have the player control movement via the map like in early Final Fantasy games(1-6). The problem is that it is currently not rendering. It was rendering just fine when I was using the x and y variables from the loop, but I need to be able to move the map around, and I don't know how I would achieve this using the loop variables. I debugged the file and all the variables were updating correctly, so I don't know why it's not rendering in the correct place.

```
public class TileMapEditor
{
   BufferedImage[] tiles = new BufferedImage[19];

   //array of tile types
   int[][] map = new int[32][32];
   //position coordinates
   public static int posX, posY;

   public TileMapEditor(int posX, int posY) throws IOException
   {
       int x = 0, y = 0;
       this.posX = posX;
       this.posY = posY;
       BufferedReader in = new BufferedReader(new FileReader("res/tileMap2.txt"));

       String line;

       while((line = in.readLine()) != null)
       {
           String[] values = line.split(",");

           for(String str : values)
           {
               int str_int = Integer.parseInt(str);
               map[x][y] = str_int;
               System.out.print(map[x][y] + " ");
               y += 1;
           }
           System.out.println("");
           x += 1;
           y = 0;
       }

       in.close();
   }

   public void update()
   {
   }

   public void render(Graphics g)
   {
       for(int x = 0; x < 32; x++)
       {
           for(int y = 0; y < 32; y++)
           {
               int textureType = map[x][y];
               BufferedImage texture = tiles[textureType];
               setTile();
               g.drawImage(texture, posX * 32, posY * 32, null);
               posY += 32;
           }
           posX += 32;
           posY = -Game.HEIGHT / 2;
       }
   }

   public void setTile()
   {
       tiles[0] = Assets.grass;
       tiles[1] = Assets.dirt;
       tiles[2] = Assets.water;
       tiles[3] = Assets.tree;
       tiles[4] = Assets.multiTree;
       tiles[5] = Assets.NSpath;
       tiles[6] = Assets.uprtPath;
       tiles[7] = Assets.EWpath;
       tiles[8] = Assets.upltPath;
       tiles[9] = Assets.dnltPath;
       tiles[10] = Assets.dnrtPath;
       tiles[11] = Assets.watgrsdn;
       tiles[12] = Assets.watgrslt;
       tiles[13] = Assets.watgrsup;
       tiles[14] = Assets.watgrsrt;
       tiles[15] = Assets.watgrsSE;
       tiles[16] = Assets.watgrsSW;
       tiles[17] = Assets.watgrsNW;
       tiles[18] = Assets.watgrsNE;
   }

}

```

# Answer
> 1 votes
My guess is that the problem is in `g.drawImage(texture, posX * 32, posY * 32, null);`

In your loops, it looks like you are manually incrementing posX, and posY. The `posX * 32` and `posY * 32` should probably be `posX` and `posY`.

`g.drawImage(texture, posX, posY, null);`

Either that, or if you want to use the x and y values of your loops then it should be: `g.drawImage(texture, x * 32, y * 32, null);`

---
Tags: java, tilemap
---


title: Screen flashing while window is open

text:
# Question
Title: Screen flashing while window is open
The screen renders everything in the right place but the entire screen flickers/flashes while it's open. Any Ideas?

TileMapEditor class

```
import com.stardust.main.gfx.Assets;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TileMapEditor
{
   BufferedImage[] tiles = new BufferedImage[19];

   //array of tile types
   int[][] map = new int[32][32];
   //position coordinates
   public static int posX, posY;

   public TileMapEditor(int posX, int posY) throws IOException
   {
       int x = 0, y = 0;
       this.posX = posX;
       this.posY = posY;
       BufferedReader in = new BufferedReader(new FileReader("res/tileMap2.txt"));

       String line;

       while((line = in.readLine()) != null)
       {
           String[] values = line.split(",");

           for(String str : values)
           {
               int str_int = Integer.parseInt(str);
               map[x][y] = str_int;
               System.out.print(map[x][y] + " ");
               y += 1;
           }
           System.out.println("");
           x += 1;
           y = 0;
       }

       in.close();
   }

   public void update()
   {
   }

   public void render(Graphics g)
   {
       for(int x = 0; x < 32; x++)
       {
           for(int y = 0; y < 32; y++)
           {
               int textureType = map[x][y];
               BufferedImage texture = tiles[textureType];
               setTile();
               g.drawImage(texture, posX, posY, null);
               posY += 32;
           }
           posX += 32;
           posY = -Game.HEIGHT / 2;
       }
   }

   public void setTile()
   {
       tiles[0] = Assets.grass;
       tiles[1] = Assets.dirt;
       tiles[2] = Assets.water;
       tiles[3] = Assets.tree;
       tiles[4] = Assets.multiTree;
       tiles[5] = Assets.NSpath;
       tiles[6] = Assets.uprtPath;
       tiles[7] = Assets.EWpath;
       tiles[8] = Assets.upltPath;
       tiles[9] = Assets.dnltPath;
       tiles[10] = Assets.dnrtPath;
       tiles[11] = Assets.watgrsdn;
       tiles[12] = Assets.watgrslt;
       tiles[13] = Assets.watgrsup;
       tiles[14] = Assets.watgrsrt;
       tiles[15] = Assets.watgrsSE;
       tiles[16] = Assets.watgrsSW;
       tiles[17] = Assets.watgrsNW;
       tiles[18] = Assets.watgrsNE;
   }

}

```

Game class

```
import com.stardust.main.gfx.Assets;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import javax.swing.JFrame;

public class Game extends Canvas implements Runnable
{
    public static final int HEIGHT = 512, WIDTH = 512;
    public static boolean running = false;
    public Thread gameThread;
    public Assets assets;
    public TileMapEditor tileMap;
    public static JFrame frame;

    public void init() throws IOException
    {
       tileMap = new TileMapEditor(-WIDTH / 2, -HEIGHT /2);
       assets = new Assets();
    }

    public synchronized void start()
    {
        if(running)return;
        running = true;
        gameThread = new Thread(this);
        gameThread.start();
    }

    public synchronized void stop()
    {
        if(!running)return;
        running = false;
        try
        {
            gameThread.join();
        } catch (InterruptedException e)
        {
           e.printStackTrace();
        }
    }

    public void run()
    {
        try
        {
            init();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        long lastTime = System.nanoTime();
        final double amountOfTicks = 60D;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;

        while(running)
        {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            if(delta >= 1)
            {
                update();
                delta--;
            }
            render();
        }
        stop();
    }

    public void update()
    {

    }

    public void render()
    {

        BufferStrategy bs = this.getBufferStrategy();
        if(bs == null)
        {
            createBufferStrategy(3);
            return;
        }
        Graphics g = bs.getDrawGraphics();
        //START RENDER

        tileMap.render(g);

        //END RENDER
        g.dispose();
        bs.show();
    }

    public static void main(String[] args)
    {
        Game game = new Game();
        game.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        game.setMaximumSize(new Dimension(WIDTH, HEIGHT));
        game.setMinimumSize(new Dimension(WIDTH, HEIGHT));

        frame = new JFrame("Tile Engine");
        frame.setSize(WIDTH, HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.add(game);
        frame.setVisible(true);

        game.start();
    }
}

```

# Answer
What you need is double buffering

I stole this from somewhere just to give you a quick answer:

"Double buffering is conceptually pretty simple, instead of drawing your objects one by one, you draw them on an image and then tell the renderer to draw that entire image. This eliminates the flickering.

Here's an example of how you might do this"

```
class DoubleBufferedCanvas extends Canvas {

    public void update(Graphics g) {
    Graphics offgc;
    Image offscreen = null;
    Dimension d = size();

    // create the offscreen buffer and associated Graphics
    offscreen = createImage(d.width, d.height);
    offgc = offscreen.getGraphics();
    // clear the exposed area
    offgc.setColor(getBackground());
    offgc.fillRect(0, 0, d.width, d.height);
    offgc.setColor(getForeground());
    // do normal redraw
    paint(offgc);
    // transfer offscreen to window
    g.drawImage(offscreen, 0, 0, this);
    }
}

```
> 1 votes

---
Tags: java, tilemap
---


# Question
Title: How would I generate random falling objects
I'm creating a game using libgdx on Eclipse that is similar to Ragdoll Avalanche. I'm looking for a way to generate falling objects like the triangles of Ragdoll Avalanche. All I know that i have to use an array but i dont know how to do it.

# Answer
If all your objects are the same shape, all you have to do is pick a location to drop them from at the top of the screen and then lower them each update either by a fixed amount or by a velocity that increases via downward acceleration (gravity)

I haven't done any android development so this will be a little generic.

The *easiest* way to handle the objects is to create them at the top at a random position. Once you've done that add it to your collection. Each update move the objects downward via the logic you prefer(as mentioned above), and when an object gets past the bottom of the screen, remove it from the collection.

Now this is by far not the most *efficient* solution, but it's a good starting point. If you end up needing more efficiency, consider doing things like not removing from the collection and instead marking ones that pass the bottom as "dead". That way when you go to make a new one, you can first see if you have a dead one to recycle.

Remember though that everything in programming is a trade, the above example adds look-up time to creation while saving you on allocation and collection resizing. Don't solve for problems you don't have.

Also I would recommend looking up information about various collection types for your language to see how they are used and what their limitations are. You likely will want something dynamic that you can add to easily, but others may be able to call out specific implementation details.
> 1 votes

# Answer
In addition to Lunin's answer:

If you're looking to use a library instead of writing you're own collision detection/physics then you should use Box2D (its what Angry Birds uses). In fact, LibGDX has a port for Box2D physics engine. It handles collision detection, and physics simulation like the ragdoll body parts and falling triangles. You can search up some Box2D tutorials and look at Box2D tests in libgdx source or the VectorPinball demo. Note that Box2D was originally written in C++. If you learn how to use Box2D for this game,I think it will be very trivial and much easier to do.
> 1 votes

# Answer
The items spawned want to be objects with intrinsic position properties and a move method that can be called every frame or every set update to change the objects position downwards. As these are instantiated you can set up the y position such that they start just above the viable screen, and use a RandomNumber\*screenwidth to determine the random x positions.

Using a loop that runs though the array you can check collisions and run the moveDown method for each object - you can also then check the positions of the objects to see if they are out of the screen to remove them, and count them up to see if you need to add more.
> 0 votes

---
Tags: android, sprites, libgdx
---


# Question
Title: In a 2D tile engine, how do I figure out which tiles are culled and which to draw?
I'm trying to make a simple 2d tile engine here, and I've got a problem with getting a proper cells from a tile grid map when I'm trying to cull off tiles which aren't needed to be drawn.

I've got a tile which is 16 by 16 pixels and a tilemap represented as a grid of 0, 1 etc

For example

```
{1,1,1,1}
{1,1,1,1}
{1,1,1,1}
{1,1,1,1}

```

Then I translate it to a Tile\[,\] matrix like this

```
public void SetMap(Int32[,] tileCodes, int sizeX, int sizeY, TileTextures tileTextures) {
        //A simple check that sizes are equal
        if (sizeX == mapBounds.width && sizeY == mapBounds.height) {
            for (Int32 i = 0; i < mapBounds.width; i++) {
                for (Int32 j = 0; j < mapBounds.height; j++) {
                    if ((TileType) tileCodes[j, i] != 0)
                        map[j, i] = new Tile(new Vector2(i, j), (TileType) tileCodes[j, i], tileTextures.GetTexture((TileType) tileCodes[j, i]));
                }
            }
        } else
            Console.WriteLine("Map.SetMap: Unable to set map of diffent size than defined one");
    }

```

So it's basically tile grid now (tile\[x,y\]), but I can't figure out, which tile I should draw. I've already got a vissible area as a rectangle (va):

```
public void Draw(SpriteBatch spriteBatch) {
        // How to get positions in tile[x,y]?
        int startX = va.area.Left/ 16;
        int endX = va.area.Right/16;
        int startY = va.area.Top/16;
        int endY = va.area.Bottom/16;

        for (Int32 i = startX; i < endX; i++) {
            for (Int32 j = startY; j < endY; j++) {
                Tile tile = map[i, j];
                tile.Draw(spriteBatch);
            }
        }
}

```

Any ideas?

# Answer
I've found a solution:

```
public void Draw(SpriteBatch spriteBatch) {
        //Interpreting tiles as bounds
        //Sub-ing and add-ing 128 just to get more tiles than visible,
        //so the world feels like more alive
        // 16 - is tile size
        // 128 / 16 = 8 more tiles
        int startX = (va.area.Left - 128) / 16;
        int endX = (va.area.Right + 128) / 16;
        int startY = (va.area.Top - 128) / 16;
        int endY = (va.area.Bottom + 128) / 16;

        //Array checks probably could've done better
        if (startX < 0) {
            startX = 0;
        }
        if (startY < 0) {
            startY = 0;
        }

        // mapBounds.width and mapBounds.Height is just array size
        if (endX > mapBounds.width) {
            endX = mapBounds.width - 1;
        }
        if (endY > mapBounds.height) {
            endY = mapBounds.height - 1;
        }

        //Drawing tiles from array
        //Since I've got transposed matrix, it's j,i
        for (Int32 i = startX; i < endX; i++) {
            for (Int32 j = startY; j < endY; j++) {
                Tile tile = map[j, i];
                if (tile!=null)
                   tile.Draw(spriteBatch);
            }
        }
    }

```
> 0 votes

---
Tags: c#, xna, 2d
---


# Question
Title: What are some good resources for learning HLSL?
The last time I tried learning HLSL, I made a few shaders and mostly understood what I was doing, but I still felt like I was stumbling in the dark. Most of what I learned I got from various blog posts that didn't explain things very well.

Also, the documentation on MSDN seems to be more of a function reference.

Where can I learn to not only write HLSL, but learn techniques for writing shaders?

# Answer
> 16 votes
Those two noted, I consistently come back to the following article almost every time I write a generic shader:

# Answer
> 6 votes
If what you are after is "shader technique", rather than mere language reference (read the question, people), I recommend (from easy to advanced):

And basically either: Try things out and practice, all while absorbing how the "pros" do things. Or pick and choose things that are similar to what you're trying to achieve and work from there.

# Answer
> 3 votes
Cg is not technically HLSL, but syntactically they are virtually identical.

Having said that, it's an older book, but NVIDIA has made "The Cg Tutorial" free to read online. It covers the basics of the programmable pipeline in a very comprehensive fashion, and it should all translate to HLSL with minimal effort.

# Answer
> 3 votes
If you want to edit and see the results real-time you can use this simple Silverlight tool

http://shazzam-tool.com/
Shazamm 1.3 - Editor & Previwer of HSLS Shaders

---

As for tutorials +1 for Riemers.net but I also found this series of XNA/HLSL tutorials even better.

Here's the list, you'll find them all here: http://digitalerr0r.wordpress.com/tutorials/

* 1 – Intro to HSLS, ambient light
* 2 – Diffuse light
* 3 – Specular light
* 4 – Normal mapping
* 5 – Deform vertex shader
* 6 – Shader demo: Simple ocean/island scenery
* 7 – Toon shading
* 8 – Gloss map
* 9 – Wiggle post process
* 10 – Invert post process
* 11 – Grayscale shader
* 12 – Pixel distortion shader
* 13 – Alpha mapping
* 14 – Transmittance/depth buffers
* 15 – Dynamic Environment mapping
* 16 – Refraction
* 17 – Point light + Self-Shadowing
* 18 – Multiple Point Lights
* 19 – Hemispheric ambient light
* 20 – Depth of Field
* 21 – Transition: Fade
* 22 – Transition: Cross
* 23 – Blur
* 24 – Bloom
* 25 – Perlin Noise on the GPU
* 26 – Bump Mapping Perlin Noise

# Answer
> 2 votes
A few things come to mind

1. Introduction to 3D Game Programming With DirectX 9.0 (awesome)
2. NVIDIA FX Composer (good for examples)
3. There was a Shader X2 intro paper on ATI's website, but it's been removed... Ah! Found it here!

# Answer
> 1 votes
I found Riemers.net has a very good introductory tutorial on HLSL as part of its XNA tutorials. The author, Riemer Grootjans, also wrote the recommendable book XNA 3.0 Game Programming Recipes \- if You like the recipe approach.

# Answer
> 1 votes
I would suggest you check the HLSL Development Cookbook , I found it to be really helpful. Especially chapter 3.

# Answer
> 0 votes
When I was reading about HLSL I found this tutorial back in the day. I liked it since it tried to explain every part of what it was doing.

# Answer
> 0 votes
I found a series of tutorials that goes from a basic ambient light shader all the way to reflections and toon shaders. Each goes through and explains every line and even explains some of the math a bit:

http://rbwhitaker.wikidot.com/hlsl-tutorials

# Answer
> 0 votes
Not sure what shader model and DirectX version you are targeting but I highly recommend Practical Rendering and Computation with Direct3D11. The book walks you through all the nitty gritty details of DirectX11, it's resources, all the different pipeline shaders, HLSL (an entire chapter dedicated to this), and how to start implementing things like particle system simulations, tessellation, image processing, deferred rendering, and DirectCompute!

# Answer
> 0 votes
I do recommend this link for examples: http://www.codesampler.com/dx9src/dx9src\_8.htm#dx9\_hlsl\_fx\_simple

For those wondering why their code won't work, or if you're confused on how to incorporate the shader into your pipeline, this is a good place to go.

# Answer
> -1 votes
for me its easier to learn GLSL first, and since HLSL and GLSL is similar. once you understand the whole concept, the pipeline, the hardware and how the inner shader language work it's easy for you to use another language such as HLSL or even Cg.

I propose GLSL because it has a very good book such as the orange and red book of openGL and its easy to learn for beginner.

---
Tags: shaders, hlsl
---


title: Random undirected graph generation

text:
# Question
Title: Random undirected graph generation
I would like to generate graphs randomly, like this:

I have read that Box2d maybe can do it to me. But I do not know how to use it, so how can I generate bodies after world initialization?

# Answer
Considering the example, I assume you mean a connected graph, i.e., there is a path from any point to any other point.

First decide if you want it to be very sparse or if the graph might need be very dense (each type prefers a different data structure).

Dense graphs are handled better by a 2D matrix of Booleans where position (j, i) is lit if `j` and `i` are connected. Sparse graphs use a list of neighbors for each vertex in the Graph. If `i` and `j` are connected, then each will be stored in the others neighbors list. I will assume it is spare because of the image example; which is all I have to go after at this point.

1. Create a struct (POD) or a class that describes a `Vertex`, it needs to store an `id` of type Int, a `position` (which is possibly two Floats) and a list of all neighboring vertices, which is an Array or List of `Vertex` named `neighbors`.
2. Randomize `N` `Position`s ( on the 2d plain) for a graph where `|V| = N` (in plain English, the number of vertices equals `N`).
3. Iterate over the random positions:
    1. Create a new Vertex from each one, with the `Position` stored as the `Vertex`'s `position`.
    2. Randomly pick a neighbor from one of the vertices created until this point (don't do it for the first Vertex as there will be no other vertices at that point).
    3. Connect the two by adding each to the others `neighbors` list.
4. To increase density, loop again and pick two vertices `v` and `u` each iteration where `v != u` and connect them until the number of edges is satisfactory to your needs. If you want a very dense graph, it is better if you assume all vertices are connected and pick ones to disconnect instead.

To draw the graph:

1. Iterate over the vertices of type `Vertex`:
    1. Draw line from their position to all the neighbors' positions if the current `Vertex`'s `Id` is lower than that of the neighbor.
    2. Draw a circle in the `Vertex`'s position.
    3. Draw the `ID` number in the center of the circle and on top of it.
> 1 votes

# Answer
You want to create a list of nodes in an array and randomize the position values. You can then make a new array to store arcs. Make an Arc object with "Start Node, EndNode" and simply store random (Different) node numbers together for each arc you want.
> 0 votes

---
Tags: libgdx
---