# Question
Title: bullet character controller sliding down any slope gradient
I've been experimenting with the btKinematicCharacterController. I've seen very old complaints that it has issues but I can't find anything recent stating that these issues remain (and nobody ever says what the issues were).

The problem I'm seeing is that the character is sliding down slopes at absolutely ANY gradient. It will only stand still on level ground. If I have a ramp with a very gentle gradient it will slide slowly. I've found posts asking about this on the Bullet forums but haven't found any solutions.

I've set the friction and rolling friction for both the ramp and character capsule to a very high value but it doesn't seem to impact the sliding. I'm sure there's something else I'm missing or is there something wrong with the controller's implementation of recoverFromPentrations (It seems to shift the object by the collision normal on the other surface which is necessary to avoid going through walls).

# Answer
> 4 votes
I'm ***guessing*** this is due to the collision resolution. Gravity pulls your character down and you start penetrating the slope. The collision is resolved along the slope normal, so you move out diagonally. Each frame the character moves down from gravity, and out slanted. You can imagine that since the resolution is slanted and gravity is downward, over time you will be pushed down the slope slowly. This is not dependent on friction.

To avoid this, don't apply gravity to the player unless he is in a non-grounded "state". This will require additional logic code.

Character controllers in physics engines can be hard.

I've also seen this problem fixed by raycasting downwards from the player during the grounded "state". Then you can always set the player's height to by standing right on the ground level. The downside to this approach is that you must code additional logic for prevent the player from walk up or down very steep ledges or cliffs. Heightmaps can make this easy, as you can just index into the heightmap array and retrieve the height at the location of the player.

---
Tags: physics, movement, bullet-physics, rigid-body-dynamics
---


# Question
Title: XNA Float values don't work as parameter
With the Microsoft XNA Framework I can change the color of a tinted texture by changing it's integer values like so:

```
Int x = 255;
if(true) { x--; tint = new Color(x, 255, 255); }
Draw(texture, Vector2.Zero, tint);

```

If x were a float however the appearance of the sprite wouldn't change until the value x became zero. With integer the texture fades over time with the event change.

Why is this? :S

# Answer
It's because of how overload resolution works in C#. Of the available constructors with three arguments, there are:

```
Color(int, int, int)
Color(float, float, float)

```

If you pass all integers, you get the integer version. But if you pass a `float` for any of the parameters, you get the `float` version (and the integers will be implicitly converted to `float`s).

The integer version takes values in the range of `0` to `255`. The `float` version takes values in the range of `0.0f` to `1.0f` for each channel (and converts them internally to cover the integer range).

(See also this blog post)
> 4 votes

---
Tags: xna, c#, color, floating-point
---


# Question
Title: Advance efficient water physics simulation
**Summary:** I am looking at creating a large(ish) ocean which multiple ships will be present in doing their own thing. I want the ocean to be a life like as possible but without compromising too much on rendering speeds.

**A Little more detail:** I am using Unity to create the game in and ultimately I will need to be able to release the game as a web player to there lies my limitations of the water simulation.
For the actual simulation of the ocean I will need it to be able to react to the ships movement and vice-versa. The end product of the simulation I want to be able to look like this simulation of a ship in water (if possible) to be done efficiently. http://youtu.be/H4ACKAUU3O0?t=3m51s

I have started reading up on other information and looked at the other similar questions to mine:
1) Water/Ocean simulation and physics
\- I have read this question fully, am looking at not using wind as said in this question but will use this as a reference when creating the final product. (I would like to add to the information from that question with the answers on this question.)

2) Resources of realistic water simulation?
\- I have started going through the tutorials that the answer linked to and so far they seem good but do not look like they will answer my question.

The water will have splashes in reaction to the objects in the water (particle effects I believe) and small waves will come off the objects in the water e.g. ripples. Also if you are a smart cookie that wants to be awesome you should include in your answer about putting a shader on the water.

**Also** since the ships will be moving all at independent speeds and traveling through the sea, for efficiency I don't want to just make the water massive so is there a way to only render/simulate the water within a certain radius from each of the ships?

**What I am looking for in an answer:**

* I would like to know the what tricks for making this type of simulation light-weight can be used for these types of water simulations and specifically in unity.
* What limitations will I encounter when creating this and why they are limitations
* The basic work flow of creating something like this step by step. (e.g. step 1: to make the object that will be in the water)
* Are there any open source projects for these types of simulations?

# Answer
> 5 votes
I only have some mild knowledge in unity, but here are some suggestions I hope you find useful.

Split the whole simulation into a few things:

1. Large waves
2. Medium waves
3. Small waves
4. Boat's reaction water
5. Water's reaction to boat

The first two can be done by moving a tiled displacement map over a plane mesh. You have a large, low detail map which represents large waves. You can tone this up for rough, stormy seas, or turn it down completely for a calm sea. The medium displacement map would be a smaller (to the scale of the ships) map which would show small waves and turbulence in the water. The effect of this would be added to the effect of the previous displacement map. You can also turn the map off when the camera is zoomed far out.

The third uses a bump map to simulate roughness in the water. Like the second map, this can be turned on only at closer inspection.

Ships should react to water via four points relative to the sea surface. Each point would be just inside the corners of the rectangle that bounds each ship at the XY (ground) plane. Each point would get the height of the water (via the large displacement map) and adjust the ship's pitch and roll accordingly. This would simulate the ship moving with the waves.

Trails left behind by a ship in the water can be simple particle effects emitted from the back of the ship and some flat animated decals along parallel to the surface (the standard triangular wave pattern.

You can forgo the second point if you want a simpler simulation. As for optimization, you can split the ocean into chunks and load them procedurally depending on what is being seen by the camera. Since the displacement and bump maps are tiled, they should line up seamlessly with each other. You may also want to look into randomizing the larger waves somehow, although I don't know how to implement that into Unity.

Hope that helps somehow! I would have posted more links in the writing to better explain some concepts, but this site is clearly too elitist or afraid of spambots.

Some additional notes:

If you want the ship's speeds to react to waves, you only need to take the large ones into consideration. Every few frames of movement, have the ship recalculate a friction variable based on the height difference of waves right at its front end, and a few meters in front of that. Since waves and ships move slowly, it should look realistic.

In that case, you may want the sea mesh deformed by some randomized noise algorithm rather than a displacement map.

---
Tags: unity, simulations, efficiency, water
---


# Question
Title: Can I create cocos2d animations without using Xcode?
I need to have someone do animation work for an iOS game I'm developing (using cocos2d), however this person does not have a Mac and as such cannot run Xcode.

Is there a way for them to create animations for me without the use of Xcode?

# Answer
No, if you are referring to writing Objective-C using the Cocos2D framework to do animations, your animator will not be able to do so without xCode. He could write the code in a text file and pass that to you, but will not be able to compile them to check that they do work (which really defeats the purpose I suppose.)

However, if you only need sprite animations then the person can create the sprite animation using flash or some such software (then export the PNG of each frame for you.) Then you can use those animation frames in your app.
> 3 votes

---
Tags: animation, cocos2d, xcode
---


# Question
Title: Entity's FSM and exposing internals of the entity
I'm trying to implement FSM according to Programming Game AI by Example, it is a pretty standard and straightforward FSM that goes like similarly to this (some stuff omitted and translated from C++ to C#, hope it's fine):

```
class StateMachine<Entity>
{
    Entity owner;
    State<Entity> state;

    void StateMachine<Entity>(Entity entity)
    {
        owner = entity;
    }

    void Update()
    {
        state.Execute(owner);
    }
}

class State<Entity>
{
    Entity owner;

    void Execute(Entity owner)
    {
        if (owner.Foo)
            owner.Bar();
    }
}

class Entity()
{
    public type Foo;
    private StateMachine<Entity> stateMachine;

    public void OnStart()
    {
        stateMachine = new StateMachine<Entity>(this);
    }
    public void Bar(){}
}

```

My problem with this state machine is that the because the state machine is not part of the class anymore (as opposed to, let's say, the naive "switch" / "if-else" implementation), it is necessary to expose internal logic of the Entity (e.g. variable Foo, method Boo()). Is this the right way to do it? What if the the Entity class grows, how does it scale. Is it really necessary to keep exposing more and more variables / creating getters/setters?

How are these FSMs implemented in larger projects?

# Answer
> 1 votes
Good question, but really the answer is that FSMs are pretty non-scalable by design. You can consider your question arising from the fact that a FSM is by nature ad-hoc and hard-codish. Usually a FSM is chosen to describe a simple and specific behavior. If you wish to do something more scalable alternative methods are going to be favorable.

I'd say this is fine. A particular state machine is going to want to know specific details of thing it is operating upon. In a "larger project" a state machine is still going to be a state machine. They are pretty simple. This is sort of like asking "what is a custom vector (array, std::vector) class like in a big code base". Well, it will be well tested, perhaps efficient and reliable, but it's still just going to be a simple vector.

---
Tags: ai, state, fsm
---


# Question
Title: Java: creating an instance of a user defined class by reading xml file
I am trying to write an engine for a game, in particular a component-based one (in my approach components contain both data and logic). So basically I have entities, and each entity has a list of components (each component extends the Component class). Now, I want to be able to define templates for my entities in xml files, and load them at runtime. The template would look something like this:

```
<Entity>
   <Component name="MovementComponent">
      <...Variables to be initialized...>
   </Component>
   <Component name="RenderComponent">
      <...Animations...>
   </Component>
</Entity>

```

The "name" attribute is the name of the corresponding component class. Now, of course the components are game-specific so I need a way to create an instance of the component and add it to the entity's list without actually knowing the specific class. I thought about Class.forName("...the "name" attribute...").newInstance(), but this way I can't add the components to the list, since it is an ArrayList of Component and the program cannot know that the object returned by the method newInstance is actually a subclass of Component. Is there any simple way to do this?

# Answer
> 1 votes
Generally I would advise the use of reflection and serialization to load component data like this. This allows you to find a class by name at runtime and to also enumerate all the fields of the class, mapping them to XML. Most existin serialization libraries use reflection already or you can roll your own if you have a very particular format in mind.

See the Java reflection docs and something like JAXB or XStream for serialization.

The simple approach you mention using `Class.forName("...the 'name' attribute...").newInstance()` is flawed, but more complete reflection usage fixes this. You can look up the class and ensure it derives from `Component` before you instantiate it and then just cast it afterwards since you know the cast will always work. You could require some specific set of annotations if you think it'll in some way help, too.

# Answer
> 0 votes
You're not likely to have too many components in your game. I suggest you set up something simple like a switch statement:

```
switch(componentName) {
     case "Movement":
        entity.AddComponent(new MovementComponent.ParseXML(componentXML));
        break;
     case "Render":
        entity.AddComponent(new RenderComponent.ParseXML(componentXML));
        break;
     ...

}

```

Each component has a function called `ParseFile` that reads all the XML contained within the `<Component>` element. This way, each component knows how to parse itself from the XML file, and parsing code is kept with the components. I set up something similar for a game of mine and it works great. I've also posted some details about it here: How smartly implement scripting in game and here Storing items in external data files

---
Tags: java, loading, xml, entity-component
---


# Question
Title: How can I apply a mesh distortion to walls like in Dungeon Keeper 2?
In Dungeon Keeper 2, the walls of the dungeon have different random shapes depending on its state (freshly dug or reinforced, and so on).

They look like they are cubes of 3x3 vertices that have a x-z planar jitter or distortion. However, the corner vertices are shared by adjacent cubes, so there must be some kind of algorithm rather than just a *random* jitter.

How could I achieve a similar effect?

# Answer
> 1 votes
The shared vertices are either not distorted, or they're distorted in the same way for adjacent cubes. When placing a new cube check the neighbor cubes to get the shared vertex position information, apply the same distortion (to make the position the same), or create a new distortion to be shared by both cubes.

# Answer
> 1 votes
I did this once using a volume texture applied in the vertex shader. The texture was a small tiling block of RGB noise.

I used the worldspace position of the vertex to look-up into the volume texture, interpreting the RGB values as a worldspace displacement vector. That way, all vertices sharing that coordinate would get the same displacement, and not peel apart.

If you do this on a surface like a wall, you'll likely want to slightly rotate/skew your coordinates passed to the texture lookup, so that the tiling is less obvious over large axis-aligned planes.

# Answer
> 1 votes
If the distortion is done in a shader it can be done by passing the world coordinates of the vertices like this:

```
uniform float strength;

void main(void)
{
   vec4 pos = gl_Vertex;
   vec4 noisePos = pos;

   pos.x = pos.x + random( vec4( pos.xyz, 0 ) ) * strength;
   pos.y = pos.y + random( vec4( pos.xyz, 1 ) ) * strength;
   pos.z = pos.z + random( vec4( pos.xyz, 2 ) ) * strength;

   gl_Position = gl_ModelViewProjectionMatrix * noisePos;

}

```

*random is not a openGL built in, see https://stackoverflow.com/a/17479300/31151 for implementations*

This will have the effect of having each vertex be offset in a pseudo-random fashion, this will also work for corners where the vertices aren't shared (different textures), because the seed is the world position.

If you are rendering multiple textures in a single mesh what I would do is pass in a per vertex `int type` (from which you can calculate/look up the UV coordinates in the fragment shader) and make the `strength` parameter an array.

Some possible improvements that might make the effect look better would be:

* Making the `strength` uniform a vec3 rather than a straight float to tweak the strength per direction (or vec2 if you only care about changing the height differently).
* Calculating the offset in a temporary vector and normalizing it, then scaling it.

---
Tags: opengl, mesh
---


# Question
Title: How can I reuse objects going off left side of screen, by putting them offscreen on the right side?
I have an array of roughly 10,000 tiles over a 2d grid. When a tile goes off screen, I'd like to recycle it by disabling the renderer, repositioning it just before it comes on screen again, then turn the renderer back on. For example, if the camera is moving right on a platformer, the tiles on the left going off screen would be recycled and repositioned on the right side just before the camera. The player could be moving in any 2d direction, up, up right, right, down right, down, down left, left, up left, thus I need to account for all directions.

```
    0,0--------------->100, 0
    | Move Direction--> |
    |                   |
   x|xxxxxxxxxxxxxxxxxxx|xxx  <-  Recycled objects taken
   x|xxxxxxxxxxxxxxxxxxx|xxx  <-  from left and repositioned on right
    0,-100<----------->100,-100

```

I've tried two approaches, one is using a wider camera view (maybe 1.3x) and using the edges with ViewportToWorldPoint and getting the player horizontal and vertical movement direction. If the camera is moving horizontally one way, my tilemanager script runs down the other side and repositions the objects on the opposite just before coming on screen. The problem here is if one is ever missed, it could go astray and then over time this leads to further problems if over time multiple are missed. I am using a tilemanager and not putting a script in each tile as it seems wasteful to have a script running in 10k+ tiles.

The other approach is literally to just scan every item in the array to see if any are outside the viewport bounding box, which seems like a huge waste of resources and not the right way to go. I have a 2d array that has just the positions saved, nonetheless scanning through any array of 10k+ each frame seems like it isn't the right way to go in terms of efficiency.

All of this work is being done as a coroutine but what is frustrating is that unity doesn't support threading as this would make this task faster as I could divide up the work more.

Is there another way anyone has used or created something that will efficiently find all objects off screen, in order to reuse them?

# Answer
> 4 votes
If I understand it correctly, you are using a different object (a plane, for example) for each tile. For several reasons tilemaps aren't usually done this way:

* As you seem to already know, it comes with massive performance issues, because you might have to render up to 10,000 tiles at once
* Things like elevated tiles, with adjacent tiles being a nice-looking slope, are very hard to do this way

Because of these and probably more reasons, you may find it useful to create these tiles out of a single mesh. There is a great tutorial on youtube which guides you through the process of doing this.

Creating your tilemap this way will resolve the performance issues you are trying to resolve by "reusing" your tiles.

# Answer
> 1 votes
You can use collision volumes. You could either set up very large volumes enclosing the play area on each side and warping the entity when the collision starts or you could make a single volume enclosing the play area and then warp the entity when the collision ends (which is the way I'd go). Generally the collision detection system will be more efficient at detecting these things than you can be in game code.

---
Tags: c#, unity, tilemap, platformer, memory-efficiency
---


# Question
Title: Creating a collision shape for a complex model
I'm currently creating the collision system for my 3D XNA game.

To check collisions with models (especially complex ones) like trees or other plants, I thought about rendering a low poly version of this object and check if the player is in collision with that low-poly shape.

I succeeded in getting all the positions of all vertices in my models. If my model is a cube, I get the 8 vertices, but how can I check if the player is inside this shape?

# Answer
This is generally done in one of two ways.

The first is to represent your object with multiple simple volumes. A tree might be a cylinder with a sphere at its top, for instance. This is not particularly accurate but may be "accurate enough." If you don't need to really worry about colliding with the branches you could even just use a cylinder or even just a bounding-box enclosing only the trunk. You can be a little "sloppy" here; you only need to be so accurate.

The other option is to actually do a collision against a mesh, usually a low-poly mesh like you mentioned. This may be taken from one of your lowest LODs (levels of detail) or it may be especially made for physics. I don't believe XNA supports this. If not, you'll need to upgrade to a real physics/collision engine; there are a number of them but I'm not sure which are the better options for C# users. Typically though you'll want to stick to the first option as it tends to have significantly better performance, though some games do actually have need for mesh-collision (shooters, for instance, but then only for things that bullets need to be able to hit).
> 2 votes

# Answer
In this tutorial (lecture 24) you can find informations about bounding spheres. In the last lecture you will see the working demo with everything set up correctly to have your character walking on a playground. You will also find the downloadable code
> 0 votes

---
Tags: xna, 3d, collision-detection, models
---


title: Floating point memory usage on gpu

text:
# Question
Title: Floating point memory usage on gpu
My question is simple: how much memory on GPU does one floating point value takes? I guess it is 4 bytes, but I'm not sure. So for example is it true that vec4, which holds 4 floats, each 4 bytes takes 16 bytes in sum.

I know this is very basic, maybe I've missed some point.

Thank you in advice.

# Answer
Usually PC gpu are 16 bytes aligned, and even a single float will take 16 bytes. If you have four floats in a struct it will get packed into 16 bytes and will be fully utilized.

The gpu compiler wont realign your cbuffer for you when they get compiled due to packing in the cpu. So packing your cbuffer right is important! ETC:

```
example 1
cbuffer
float
flaot2
float

Will be 16 bytes.

example 2
cbuffer
float - 16bytes ( bad packing )
int4 - 16bytes
float - 4bytes, this two will be packed into a 16bytes flaot4
float - 4bytes
and 8 bytes of unpacked
float4 + 16 bytes

will be 64 bytes

```

So, a float is never 16bytes unleass it´s packed.
> 2 votes

---
Tags: opengl, mathematics, memory
---


# Question
Title: How do I calculate market share in an economic simulation?
I want to make a game in which the players create different products (supply), and I give them a certain finite number of customers (demand). Players can choose the price and quality of their products (among perhaps other variables).

I've been trying to come up with an algorithm to decide on the market share of each product based on those variables. I could do something random, but thought I'd ask first!

# Answer
> 3 votes
You can do this quite effectively with the following approach:

* Give each product an "attribute vector" (quality variables such as amount of crunchiness, whatever....)
* Create pool of 1,000 customers or so to represent the market
* Give each customer a "taste vector" - i.e. how much they value each product attribute
* Each customer evaluates all products, and chooses the product where **the dot product of the taste vector with the attribute vector minus the price** is highest (if this is still negative... the customer opts not to buy anything)

If you want to add in more real world market features you can also try:

* **Customer stickiness** \- customers stick with the previous product they purchased X% of the time (chosen randomly).
* **Brand perception** \- make the actual attributes of the product different from the perceived attributes of the product.
* **Novelty effect** \- if a product is new and well-marketed, customers may buy it once anyway regardless of their preferences (this typically only applies if the purchase is relatively small, of course...)

---
Tags: algorithm, economy
---


# Question
Title: Lunar lander: why is my descent module crashing
I've been reading this awesome simulation of the actual Apollo 17 descent: http://www.braeunig.us/apollo/LM-descent.htm

I've been trying to make my own simulation using Euler integration, with a time step of 100ms. The problem is my descent module is crashing during the first two minutes with a vertical speed of -220 m/s.

During the initial stage of the descent (braking), the lander is tilted 90º and almost all the thrust is spent in the horizontal component, with no force to counter gravity. In my simulation the vertical speed quickly builds up while the pitch is 80-90º, and then gravity does it job. Here's a trace:

```
    t: 0 s;  x: 0;   y: 17234.6112;  vx: 1697.1264 m/s;  vy: -20.4216 m/s;   ax: 1.2995855485404475 m/s2;    ay: -1.6121564579144938 m/s2
        pitch: 90;   throttle: 0.1297;   fuel: 8874.2Kg

    t: 10.015 s;     x: 17062.974621379497;  y: 16948.14950433809;   vx: 1710.2669538608811 m/s;     vy: -36.64853435841286 m/s;     ax: 1.3247309786564347 m/s2;    ay: -1.628484797082333 m/s2
        pitch: 90;   throttle: 0.1297;   fuel: 8855.501190599978Kg

    t: 20.019 s;     x: 34239.89169813059;   y: 16498.912567960208;  vx: 1723.6514116543285 m/s;     vy: -53.026163503416676 m/s;    ax: 1.3509707026458686 m/s2;    ay: -1.6456786784409965 m/s2
        pitch: 90;   throttle: 0.1297;   fuel: 8836.82291908347Kg

    t: 30.026 s;     x: 51527.03405575163;   y: 15884.74450896862;   vx: 1725.5675762461628 m/s;     vy: -69.5834660661016 m/s;  ax: -0.9584923539027193 m/s2;   ay: -1.663174744204344 m/s2
        pitch: 90;   throttle: 1;    fuel: 8756.011226046036Kg

    t: 40.041 s;     x: 68759.3217349438;    y: 15103.315677459259;  vx: 1715.7571868391299 m/s;     vy: -86.32821281208818 m/s;     ax: -1.0003892381595199 m/s2;   ay: -1.6806337716945954 m/s2
        pitch: 90;   throttle: 1;    fuel: 8611.841531365935Kg

    t: 50.502 s;     x: 86651.75776002374;   y: 14107.047450672597;  vx: 1705.0564069549016 m/s;     vy: -104.00697912916615 m/s;    ax: -1.0452064683102156 m/s2;   ay: -1.6991809596193168 m/s2
        pitch: 90;   throttle: 1;    fuel: 8461.251498809865Kg

    t: 134.865 s;    x: 226365.92349700694;  y: -5.915270639694082;  vx: 1602.384872970266 m/s;  vy: -225.9485740506923 m/s;     ax: -1.382111636427434 m/s2;    ay: -1.224439728661491 m/s2
        pitch: 78;   throttle: 1;    fuel: 7246.814359289593Kg

    FINISHED at t=2.24775 minutes

```

However, in the original simulation, vertical speed never exceeds -20 m/s. I don't know how could this be possible, as there's no drag due to atmosphere. And I've coded initial acceleration and velocity values exactly as in this very same page. You can check the original trace here:

http://www.braeunig.us/apollo/LM-descent.pdf

Here we can see the Moon's gravity is aprox. -1.5 m/s which heavily influences `ay` in my simulation. However in the real descent trace it was kept to lower values (+-0.1) most of the time, even during the first minute when there was no vertical thrust due to the engine.

I must be making very stupid mistakes but right now I can't see where.

BTW this is how I update my vars in each step:

```
    //Calculate acceleration as a function of mass, velocity, thrust and gravity
    ax = vx*vx/(y + MOON_MEAN_RADIUS_M) + (thrust_x/mass);
    ay = (vx*vy/(y + MOON_MEAN_RADIUS_M)) + g + (thrust_y/mass);

    // This would be the acceleration for a flat moon. Don't work either.
    //  ax =  thrust_x/mass;
    //  ay = g + (thrust_y/mass);

    //Update velocity as a function of acceleration and time.
    vx = vx + ax*dtSecs;
    vy = vy + ay*dtSecs;

    // Update position
    x = x + vx*dtSecs;
    y = y + vy*dtSecs;

```

Any hint would be appreciated.

Thanks in advance.

# Answer
You have switched the two acceleration formulas around, and you forgot a negation, so:

```
ay = vx*vx/(y + MOON_MEAN_RADIUS_M) + (thrust_x/mass);
ax = -(vx*vy/(y + MOON_MEAN_RADIUS_M)) + g + (thrust_y/mass);

```

Basically this is computation of the centrifugal force.

But the centrifugal force isn't really a force, it is just an artefact of using a rotating coordinate system.

So a better way to explain it may be that it is a confusing way of introducing coordinate system rotation. As the rest of the simulation presume that the coordinate system is aligned according to local gravity, the coordinate system has to rotate with the landers movement around the Moon.

Calculating new coordinates when rotating a coordinate system by an angle of `α` counter-clockwise:

```
x' = cos(α)x + sin(α)y
y' = -sin(α)x + cos(α)y

```

But we would only ever turn the coordinate system by a very small amount, so small that it is acceptable to use limits to simplify the formula:

```
for α → 0
sin(α) → α
cos(α) → 1

```

Now we need to know what `α` is, that depends on the landers horizontal movement and the distance to the centre of the Moon:

```
α = dx / [distance to Moon]

```

Where `dx` is the amount `x` changes.

In total in code with clockwise rotation in the positive direction we get:

```
vx = vx - vx * timestep / moondist * vy
vy = vx * timestep / moondist * vx + vy

```

That can be shortened to:

```
vx += -vx * timestep / moondist * vy
vy += vx * timestep / moondist * vx

```

And as the job of acceleration in code is to be multiplied by `timestep` and added to velocity it is easy to integrate this into acceleration.

### About the task

I find two things wrong about this task. First of all giving you a "magic" formula with no explanation doesn't help you to learn the relevant mathematics. Second, who the hell use rotating coordinate systems in simulation? Stick to one reference frame and resign to the fact that up and down are not universal directions. It is so much easier in the long run.
> 2 votes

---
Tags: physics, trajectory, euler-method
---


# Question
Title: Why isn't this UIButton visible in Xamarin.iOS?
I'm trying to implement buttons into my game. I noticed iOS has the `UIButton` class, which I tried, but upon drawing it nothing is shown. The asset image is properly loaded, I've checked this. The `SpriteBatch` isn't drawing on top of the buttons either. `Draw` is properly being called on every frame. The button's enabled property is set to `True`.

The code, simplified:

```
private List buttons;

public void AddButtons()
        {
            UIButton b = new UIButton(UIButtonType.Custom);
            b.SetBackgroundImage(UIImage.FromBundle("icon.png"), UIControlState.Normal);
            b.Frame = new System.Drawing.RectangleF(0, 0, 256, 256);
            buttons.Add(b);
        }

    public void Draw()
    {
        foreach (UIButton b in buttons)
        {
            b.Draw(b.Frame);
        }
    }

```

Why isn't it visible?

# Answer
At no point in the code above do you call the equivalent of addSubView:, which I think (assuming `this` is a `UIView`) should be `this.AddSubView(b)`.

Pre-supposing Xamarin's iOS implementation works the same way that the underlying Objective-C APIs work, you would also no longer need to explicitly call the `Draw` method of the buttons because that will be handled by the UI Kit machinery that Xamarin's API is wrapping.
> 1 votes

---
Tags: c#, ios, gui, monogame
---


# Question
Title: How do I synchronise real-time moves of players on a grid?
I'm working on a real-time game based on a grid. Each player can move a single square at a time. A server tracks the game state and notifies clients of changes.

It's possible for two players to make a conflicting move, such as attempting to move to the same square. **How can I fairly resolve such conflicts when they happen?**

My current approach is *First come, first served*: When the server receives a move, it immediately updates the game state to reflect that. It then discards any conflicting moves it receives later.

---

The problem is that the *moment a move was received* does not necessarily line up with *moment it was sent*. Players on a faster network connection will always have an advantage.

How can I deal with this?

# Answer
One approach to more fairly resolve conflicts would be to make the server logic work in turns, with very short fixed-time turns so play still proceeds in realtime.

During each turn, the server collects all moves, but doesn't immediately commit them to the game state.

A moment later, it closes the turn, detecting & resolving any conflicts in the moves received that turn and committing the result to the game state, updating clients as needed.

This way you can implement any conflict resolution strategy you want - pure random, alternating, influenced by unit rank or perks applied, etc...
> 1 votes

# Answer
You could have all players *send a timestamp with their moves*. The server waits, collecting all players' incoming moves (or until some maximum latency), sorts them by timestamp executes them (applying the result to the game state), while discarding conflicting moves. It then notifies all players of changes and waits for another set of moves.

This way, players on slow connections are still treated fairly.

---

The only issue with this I can think of is that network-savvy players could cheat by forging their timestamps such that they always get the highest-priority move...
> 0 votes

---
Tags: networking, multiplayer, client-server, lag, realtime
---


# Question
Title: How do I efficiently render the tiles of a tile map?
I've been working on a game, and I've been using Python with Pyglet to create it. I had an issue on how I could do effective tile based rendering. I tried cocos2d, however the API is very efficient and doesn't support maps which are larger than 1000x1000 tiles. I did some further research, and found you could make it so when you triggered an update, only sprites on the edge of the screen would update, however it is still buggy (it's not fully working).

Here is my code, and here's some relevant rendering code:

```
self.camera[0]-=amount
for a in range(self.window.height//self.block_size):
    self.sprites[(self.camera[0]//self.block_size)-1][a+(self.camera[1]//self.block_size)].batch = render
    self.sprites[self.window.width//self.block_size+(self.camera[0]//self.block_size)+1][a+(self.camera[1]//self.block_size)].batch = None

```

What approach should I use to render maps larger than 1000x1000 tiles?

# Answer
> 2 votes
To support drawing tile-based map of arbitrarily large bounds, you want to take the approach of *not rendering* every tile all the time. You only need to attempt to draw what the player could see, any other draw attempts are a waste of processing time and resources. This is an API-agnostic approach and it doesn't matter whether you are using Pygame, cocos2d, or any other API.

To accomplish this feat, you need to know some information that is basically an extension of that you'd need for handling scrolling in a side-scrolling platformer.

You need to know

* the position in within the global tile map that the player is looking at,
* the size (in tiles) of the visible around centered around that look position

Every update you simply compute the bounding rectangle that describes which tiles are visible based on those two pieces of information and submit *only those tiles* for rendering. To re-use the code snippet from my answer in the above-linked question, you compute

```
var viewportLeft = focusPoint.X - (viewportSize.Width / 2);
var viewportRight = focusPoint.X + (viewportSize.Width / 2);
var viewportTop = focusPoint.Y + (viewportHeight / 2);
var viewportBottom = focusPoint.Y - (viewportHeight / 2);

```

and draw only the tiles bounded by the above four variables.

If your game support smooth scrolling of the tile map, rather than tile-by-tile scrolling, you may want to expand the viewport width and height slightly to account for the potential overlap.

To efficiently render the set of tiles you know about, you want to minimize state changes and draw calls. Ideally, your actual tile sprites are stored in a texture image, a specific type of texture atlas where all the images in the atlas fit on grid. This allows you to have only that one texture and related shader bound, minimizing those state changes.

To reduce draw calls, you want to have all the geometry for all the tiles you are going to render in as few vertex buffers as possible. If you are using the 2D sprite rendering functionality of your higher-level API, most of those will support the batching of geometry (and state changes, for that matter) in their "sprite batch" style classes if they have `begin` and `end` type members. If not you may need to do it manually, usually by making use of a dynamic vertex buffer which you refill with the tile vertices, texture coordinates, and so for all the appropriate tiles every frame.

---
Tags: rendering, python, pyglet
---


# Question
Title: How do I reverse the playback of an animation (instead of restarting it)?
I have created a sprite sheet of which consists of six frames of a character whose legs move each frame. Now I have written code so that the animation is running successfully from frame one to frame six, however I am trying to *reverse* this so then instead of looping back to frame one after the last frame, the animation moves backwards from frame six to frame one and then repeats in a continuous loop.

I handle the animation currently like this:

```
void SpriteGame::Update(int tickTotal, int tickDelta)
{
    if ( tickTotal >= this->playerLastFrameChange + 4)
    {
        //Four ticks have elapsed since the last frame change
        this->playerFrame = this->playerFrame + 1;
        this->playerLastFrameChange = tickTotal;  //We've just changed the frame

        if (this->playerFrame >= this->playerSheetLength)
        {
            this->playerFrame = playerLastFrameChange + 4;
        }

        //Frame has changed so change the source rectangle
        this->playerSourceRect->left = this->playerFrame * 64;
        this->playerSourceRect->top = 0;
        this->playerSourceRect->right = (this->playerFrame + 1) * 64;
        this->playerSourceRect->bottom = 64;
    }
}

```

How can I accomplish this using Direct3D 11?

# Answer
> 1 votes
```
bool forward=true;

( tickTotal >= this->playerLastFrameChange + 4){
//Four ticks have elapsed since the last frame change
 if(forward)
  this->playerFrame = this->playerFrame + 1;
 else
  this->playerFrame = this->playerFrame - 1;
}

```

Just add a boolean indicating which direction you are currently moving in. Depending on this you in- or decrease the current frame. You need to set the boolean to false, after you reached the last frame (to move back again) and to true after you reached the first frame again.

This will oscillate between back and foreward

# Answer
> 1 votes
A more general way to handle this would be to insert an abstraction layer between the animation and the frames of the animation on your sprite sheet.

Right now, you are just assuming that an animation consists of the sequential playback of frames 1 through frame *N* of some sprite sheet, and now you'd like to change that to the meaning is "frames 1 through *N*, and then frames *N - 1* through 1 in reverse." floAr's answer (introduce a variable indicating whether the animation is traversing frames forward or backwards) is perfectly acceptable and will do exactly what you want.

What I propose is a more generalized approach where an animation is a list of *arbitrary* frame numbers from the sprite sheet (instead of the implicit sequential list you are currently working with). This requires additional data and as such as a slight overhead in terms of memory and content creation time.

To accomplish this, you'd read the list of frames (which I will call an "animation sequence") from a data file (which can be as simple as a text file), which might look like this:

```
//walk_animation.txt
1 2 3 4 5 6 5 4 3 2 1

```

This file (`walk_animation.txt`) defines each frame of the animation, space-separated, as a number which refers to a sprite index in the sprite sheet. Frames 1 through 6 of the animation correspond exactly to sprites 1 through 6 in the sheet, but frame 7 of the animation is sprite 5, 8 is 4, and so on.

At the cost of some additional data overhead, this approach allows you keep your current, simple animation code (that just loops the animation). It also affords you the flexibility of using an entire sprite sheet for potentially many distinct animations, and easily having variants of an animation (for example a "fast" and "slow" punching animation, whether the "fast" animation omits some less-than-critical frames).

---
Tags: c++, directx11
---


# Question
Title: How do I play an animation using lib3ds?
I am having trouble playing an animation of a `.3ds` object using lib3ds.

I am able to load the .3ds model with lib3ds. But I can't find a way to play (for example) my 'walk' animation. Where can I find the animation data and how can I play the animation using lib3ds?

# Answer
lib3ds only provides access to the data within `.3ds` files, along with some utility functions. It does not appear to have any kind of built-in playback functionality. You will need to build that yourself, but to do so you will need to access the data that lib3ds has loaded up.

lib3ds exposes `Lib3dsTrack` objects for various nodes in the file which define keyframe tracks for various attributes of the node.

You are probably interested in the tracks of `Lib3dsMeshInstanceNode`, which are:

```
Lib3dsTrack pos_track;
Lib3dsTrack rot_track;
Lib3dsTrack scl_track;
Lib3dsTrack hide_track;

```

These tracks define keyframes for position, rotation, scale, and visibility of the mesh. The keyframes are of type `Lib3dsKey` and contain value information as well as flags indicating which *type* of value information to use for that key (not all keys have sane values in all value fields).

There are various utility functions (in the `track_eval_*` family) that allow you to evaluate the value of some specified track at some specified time *t*, which can help you in processing the data in the tracks so you don't have to do it all yourself.
> 1 votes

---
Tags: animation, 3dsmax
---


# Question
Title: 3D rotation and movement of ball on a 2D plane
Here is a video of Amiga arcade pool game: https://www.youtube.com/watch?v=zTQIPFBUFIg
I am making a similar game with C and Gtk+3.0 but I don't know how to show balls 3D movement on 2D plane!
I guess there is some tricks with changing image of the ball but I don't know exactly what to do.
I can move the balls on 2D plane but I can't show their rotation!
how did they show 3D movement of ball in Amiga's pool game?

# Answer
This type of effect is commonly done by creating a sprite sheet with the various angles pre-rendered. Then the game switches between the various sprites depending on what the angle of the ball is.
> 0 votes

---
Tags: 2d, 3d, animation, graphics-programming
---


# Question
Title: How should I handle sprite creation for customizable 2D characters?
I'm want to create avatar animations (sprites) for a browser-based MMORPG. The player is able to customize the character, and the content changes often (new weapons, armors, and so on). How can I structurally manage the creation and updating of all the sprite sheets?

The amount of different combinations are big enough that simply generating all permutations won't work.

This can be server- or client-based, but if it works entirely on the client, please keep it to just HTML5/CSS/Canvas/WebGL.

# Answer
To do this effectively without 'generating all possible options,' you're going to want to use a layering approach... at least in theory, even if in practice you eventually collapse the layered textures to a single sprite for draw-call reduction, which I think you should and will detail later.

The layering approach involves having a sprite set for all your characters without weapons or gear, and individual sprite sets for each weapon or gear aligned in such a way that they can be rendered overtop the base character sprites to form the final, composited character.

For simple sprites with few viewing angles (like the battle sprites of traditional Final Fantasy games), this is relatively easy. For more complex sprites (such as the characters of Diablo II, which had multiple facings and an isometric perspective), the weapon and armor sprites will be more difficult to construct because you must leave "gaps" in the sprite when it would appear behind the character. A simple way to alleviate that issue is to allow the equipment sprites to be further subdivided into a "foreground" and "background" layer. Your process for rendering a sprite is then logically:

1. Render the gear background layers (usually only weapons).
2. Render the base character sprite.
3. Render the gear foreground layers (usually mainly armor).

This method is not fool-proof (especially as you increase the number of independently-interchangeable pieces of gear that can be equipped and also impact a rendered character), but it will work for a large majority of the equipment once your artists get the hang of the authoring technique.

A sprite-editing tool with toggle-able layers will be critical because it's hard to animate a sword or staff being swung through empty air without a reference layer of the character swinging it. If your sprites are actually created in a 3D tool, it can be *much* easier to get this pipeline set up.

You could use this technique in it's vanilla form as described above. However, you should be aware that it means increasing the number of draw calls per on-screen character *significantly*, which can be a serious problem in an MMO where once must at least account for the possibility that many characters will be on-screen at a time.

*Baking* the combined layer render into a single sprite sheet is a useful tool to combat this problem. You should have some code that will perform the above rendering steps to a texture which you can save to disk or cache in-memory. That way you can pay the increased render cost once, any time a player switches their gear, but after that initial render you switch to using the baked composite texture sheet for all subsequent frames.

For maximum runtime efficiency, make sure all the sprite sheets for character and gear align exactly so you can just render the *entire* sheet and not individual frames. You can use various forms of off-line bin-packing to maximize the layout of sprites on the sheet, as well as texture compression, to save off-line space.

It's also possible to leverage this technique during your game's content build: characters with fixed gear, such as NPCs, can be pre-baked to save some run-time (particularly for characters which might appear frequently).

You will also want to make sure your game as a way to report to any player the base character type and equipped gear of *other* players nearby, so that you can pre-emptively do the compositing on a client's machine for when those nearby players eventually come into view of the local player.
> 14 votes

---
Tags: sprites, browser-based-games, spritesheet, avatar
---


# Question
Title: How to manage game objects, npcs, items?
i'm making a small 2D game, designed the maps with Tiled, and adding "basic" world object/items/npcs/mobs to test it a bit and have fun. Now i have encountered a relatively huge problem, with further development of the world, as our small team has grown by 3 volunteers we have to cover large amounts of (note most of this data, other than AI, is JSON)

* quests
* items
* npcs
* mobs
* skills
* armor
* weapons

we tried to keep track of the editing with revisions, comments, we also used milestones for patching/fixes/hotfixes, and so on.

Our basic tools:

* Spreadsheet, which has served well but we discovered that we can't do much with revisions of on a game item or weapon.
* we also tried Redmine, but other than issues, this doesn't serve our needs

Can some suggest and alternative way of managing this, or any opens-source tool? that will just make our development a bit easier, than the pain that its right now.

Or is one of those situations that we need to develop a specific tool for our needs?

# Answer
> 1 votes
I recommend that you use any text format that is readable enough for you and then use a decentralized source control manager such as Git.

Then people can work on their own and push their changes to everyone else when ready, and with good "diff" tools etc. Look up the tool "gitk" for a GUI version.

# Answer
> 1 votes
Did you try to use a wiki? It's collaborative and it saves revisions. You can try https://www.atlassian.com/software/confluence which is easy to setup and costs 10$ a year for 10 users or 10$/mo for a hosted solution. Of course you can use any open source alternative like Mediawiki or something simpler

# Answer
> 1 votes
Sounds like you simply want to save your files in a text format and source control to merge changes.

Excel is particularly bad for cooperative work, same goes for any Office product (not just Microsoft Office). The problem being that no two people can work on the same document, at least not with lots of hassles. Plus you still have to export the data in a readable format.

Wikis aren't designed for creating and exporting game data in the first place, so don't even begin to look into those. They do however work well to share documentation and knowledge.

As for the text-based data format try to avoid XML because unless properly formatted it'll be a merge nightmare with source control. It will also require you to use a proper XML parser that provides good error reporting, otherwise you'll find yourself chasing an extraneous angle bracket inlined somewhere in regular text.

Any basic text format (ie INI style) suffices. I personally find Lua scripts and specifically Lua's table data structure to be very powerful because you can not just declare data in a text file but you can also programmatically create and (if needed) verify it, avoiding lengthy and error-prone copy & paste editing.

---
Tags: 2d, project-management, scalability, world-design
---


# Question
Title: How can I export models from 3DX Max into XNA?
I am looking for a way to import my 3D models (including materials and shaders) from 3D Studio Max to XNA.

For example, if I have a model with diffuse, bump, reflection textures and values (through Max's basic shader), I want to be able to present it in real-time using the XNA framework.

I thought about doing it like this:

1. 3D Studio Max -\> ASCII FBX export.
2. Parse FBX and extract bump/reflection/et cetera textures.
3. Set up a custom HLSL shader and pass the relevant parameters to it.

Is this the correct way to do it?

# Answer
I would export from Max into a format that XNA can already handle (such as FBX), parsing out any data not normally handled by XNA and handling it manually. Essentially this is exactly the process you put forth, so *yes*, that is a reasonable approach.

You may also be interested in the work Tim Jones did back in 2010 to create content importers for XNA that supported 3DS (and other) formats. The code is available here via his GitHub account.
> 2 votes

---
Tags: xna, shaders, hlsl, 3dsmax, xna-content-pipeline
---


title: Avatar creation / dressing feature

text:
# Question
Title: Avatar creation / dressing feature
What is the effort required to use a game engine such as Unreal or Unity, etc. and create an avatar customization features...complete with clothes.

The user should be able to customize the body features and the clothes need to then fit onto the customized body.

What is needed? Can you create one set of 3D models for clothes and somehow programatically have the clothes adapt to the body shape? I.e. The same shirt model will be able to fit on a skinny person vs. someone with a big beer belly.

How difficult is this? What are the steps needed to implement this avatar creation/dressing feature.

I'm basically talking about something like in Rockband 3.

# Answer
In a general sense, the engines like Unreal or Unity provide you a way to get your assets on the screen. They may have tools for mashing up a bunch of assets, but you still need a program like Maya, 3D Studio Max, or Blender to build the assets you're going to be mashing up.

Specifically, to answer your question on effort: the effort required is probably significant, but not insurmountable. It depends on your skills and dedication. If your a programmer, building the 3D models for each of the items you want will probably be the area you spend the most effort; on the other hand, if your already adept with a 3D modeling package, and aren't much of a programmer, you'll find yourself struggling with any engine.

The steps required, in my view are: (assuming you're starting from absolute zero)

* Get one full-body 3D model
* Get one full set of 3D clothing models
* Download / Install the Unity or Unreal SDK
* Get a working creation model
    + Using the scripting built-in to the engine to develop an interactive system
* Obtain all other full-body 3D models and associated clothing items

Note the unordered list, most of these can happen asynchronously, though if its just you working on it, it would probably make sense the serialize the process.

This is a relatively large task, that will probably require significant effort, and is probably (at least in my opinion) not a good place to start building games, I'd recommend biting off a smaller project if this is your first.
> 2 votes

# Answer
Unity has an example project with this already implemented for you:

http://unity3d.com/support/resources/example-projects/charactercustomization

On that page it says "feel free to use the code and artwork for your own Unity productions", which would likely reduce the workload significantly (since it's already done for you!)
> 5 votes

# Answer
I would do this by scaling and moving specific armature bones (in case your program has mesh skinning implemented). For example, if you want longer legs, scale the leg "bones" (which are also used in your animation) by the up axis. If you want to increase the weight, scale some bones by the horizontal axes, for example.

However if you scale non-uniformly then you can not decompose your matrices correctly, so you should keep scaling - rotation - translation of your bones accessible.
> 0 votes

---
Tags: avatar
---


# Question
Title: Where can I find info on grid based algorithms for stateless AI?
There seems to be an overwhelming amount of info out there on AI of all kinds, and it's kind hard to digest at once.

For my testing purposes, I'm creating a "typical stateless AI", as described in this article, and now I need to implement the following functions for a 2D square based game board:

```
-(void)runAway;
-(void)attackPlayer;
-(void)moveTowardsPlayer;
-(void)tacticalMoveAwayFromPlayer;
-(void)waitOrStationaryAction;

```

For example, I can run my own run away function like this:

```
-(void)runAway
{
    DLog(@"runAway");
    [self debugMessage];

    int bestTileIndex = 0;
    int largestDistance = 0;
    int distance = 0;
    if(validMoves.count>0)
    {

        for(NSNumber* tileNumber in validMoves)
        {
            distance = [self distanceToTargetFromTile:tileNumber.intValue];
            if(distance >largestDistance)
            {
                largestDistance = distance;
                bestTileIndex = tileNumber.intValue;
            }
        }
    }
    //move to best tile

}

```

but this method only checks the distance from 1 target, which may not be the best if there are multiple enemies on the game board.

**Where can I find good/efficient implementations of algorithms for searching a 2D grid for these functions?** For example finding a point that is furthest away from multiple opponents and is accessible within a certain number of moves.

Other functions that come to mind is picking the best/weakest target, moving towards a specific target while accounting for variable terrain cost, etc

I'm certain someone has already done this before.

# Answer
I don't give you a plain code, but I give you idea and some food for brain. I think it depend on the game, for example if you have a large board with big amount of tile this one thing, but if you have 10x10 board, there is nothing bad to iterate through the tiles for 4 or 8 (with diagonals) directions. iOS devices extremely productive and this won't overload cpu and don't take a long time to go through all possible moves. I made such a thing when I make my reversi game Fresh Reversi, you can check out free version.

For example, you can create a method to go to one direction from your AI player (let's go right), this will be a cycle, and we go while we not away from board or if we found player. So, each iteration you can count tiles for distance and so on. After you find player you can save this possible move to dictionary and call another method for another direction and so on. Hope you got my idea. This is not panacea, but I think it's good for board game type.
> 0 votes

---
Tags: algorithm, ai, objective-c, grid
---


# Question
Title: How would I detect if two 2D arrays of any shape collided?
Say there's two or more moveable objects of any shape in 2D plane, each object has its own 2D boolean array to act as a bounds box which can range from 10 to 100 pixels, the program then reads each pixel from a image that represents it, and appropriatly changes the array to true(pixel has a alpha more then 1) or false(pixel has a alpha less than one).

Each time one of these objects moves, what would be the best accurate way to test if they hit another object in Java using as few APIs/libraries as possible?

# Answer
You could use actual bounding shapes instead of per-pixel collision data (you incorrectly called it a "bounds box"). This greatly simplifies the computational requirements.

You can use a single primitive shape in most cases, e.g. an AABB (axis-aligned bounding box), circle, etc.

If you need (actually need, not just think you need with no analysis) more complex shapes, you can achieve those in several ways. The first is to allow multiple primitive shapes. A table side-view for instance can be represented by three AABBs: one for the top and one for each pair of legs. A tree is an AABB with a circle at the top. etc.

The second option is to use a polygon shape. Generally this will be a convex hull as the math is considerably simpler for convex hulls than for arbitrary polygons. Again you can use multiple shapes (potentially all convex hulls or a combination with other primitive shapes) to represent more intricate objects that cannot be accurately represented by one. A human character may have separate polygons for each limb apart from its head and torso, for instance.

Typically you really, *really* don't need per-pixel collision, especially if you support convex hulls. You can represent any object with a set of convex hulls. The results will be faster and easier and allow more things to be done with them (such as determining depth of overlap and so on).
> 3 votes

# Answer
What you essentially have is per pixel collision. Each of your array locations represent a pixel, I'm assuming that you have arbitrary shapes defined in these arrays. I'll assume an array position holds `true` if it's solid and `false` if it's not.

You check collisions by iterating through one array (the smaller preferably) and checking to see if any of its `true` values overlap with a `true` value in the second array.

```
vec2 diff = getOffset(array1, array2) //get the distance between the two arrays
for x = 0 to array1.xsize
    for y = 0 to array1.ysize
        if array1[x,y] //for each position, if it's true
            if array2[x-diff.x, y-diff.y]//if array2 has a true in the overlap position
                return collision

```

You'll find some optimizations for other collision detection strategies work here too. For example, first finding your min/max values and creating a proper bounding box. Then you can just check if the two bounding boxes overlap before doing anything.
> 0 votes

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


# Question
Title: When and how should I update my collision grid?
When and how should I update my collision grid?

Current implementation:

1. buildGrid(): add all entities with collision to the grid
2. handleCollision(timePerFrame, entities): handle all collisions
3. grid.clear(): clear grid

If I have for example 4000 stationary entities and only 20 moving entities, I remove and add 4000 entities to the grid every update for no reason.

What would be the good way to update only cells that require updating?

Only idea that I have currently is that after collision check I remove moving entities from the grid and during buildGrid() I add only moving entities to the grid.

All help is welcome.

Grid implementation

```
// CollisionGrid Cell
class Cell
{
    public:
        typedef std::set<Entity*> Container;

    public:
        void        setNeighbours(Cell* left, Cell* right, Cell* up, Cell* down);
        void        addEntity(Entity* entity);
        Container   getNearbyEntities() const;
        void        clear();

    private:
        void        appendEntitiesTo(Container& entities) const;

    private:
        Container   mEntities;

    protected:
        Cell*       mLeft;
        Cell*       mRight;
        Cell*       mUp;
        Cell*       mDown;
};

// CollisionGrid
class CollisionGrid
{
    public:
                            CollisionGrid(float sceneWidth, float sceneHeight, float cellSize);

        void                clear();
        void                addEntity(Entity* entity);
        Cell::Container     getNearbyEntities(Entity* entity);

    private:
        int                 getIdForPosition(const sf::Vector2f position);

    public:
        int                 mCols;
        int                 mRows;
        std::vector<Cell>   mCells;

    private:
        float               mSceneWidth;
        float               mSceneHeight;
        float               mCellSize;
};

// CollisionGrid Cell
void Cell::setNeighbours(Cell* left, Cell* right, Cell* up, Cell* down)
{
    mLeft = left;
    mRight = right;
    mUp = up;
    mDown = down;
}

void Cell::addEntity(Entity* entity)
{
    mEntities.insert(entity);
}

Cell::Container Cell::getNearbyEntities() const
{
    Container entities = mEntities;

    if (mLeft != nullptr)
        mLeft->appendEntitiesTo(entities);
    if (mRight != nullptr)
        mRight->appendEntitiesTo(entities);
    if (mUp != nullptr)
        mUp->appendEntitiesTo(entities);
    if (mDown != nullptr)
        mDown->appendEntitiesTo(entities);

    return entities;
}

void Cell::clear()
{
    mEntities.clear();
}

void Cell::appendEntitiesTo(Container& entities) const
{
    entities.insert(mEntities.begin(), mEntities.end());
}

// CollisionGrid
CollisionGrid::CollisionGrid(float sceneWidth, float sceneHeight, float cellSize)
: mSceneWidth(sceneWidth)
, mSceneHeight(sceneHeight)
, mCellSize(cellSize)
, mCols((int)floor(sceneWidth / cellSize))
, mRows((int)floor(sceneHeight / cellSize))
{
    mCells = std::vector<Cell>(mCols*mRows);

    for (int id = 0; id < mCols*mRows; ++id)
    {
        Cell* left = nullptr;
        Cell* right = nullptr;
        Cell* up = nullptr;
        Cell* down = nullptr;

        if (id % mCols > 0)
            left = &mCells[id - 1];
        if (id % mCols < mCols - 1)
            right = &mCells[id + 1];
        if (id > mCols - 1)
            up = &mCells[id - mCols];
        if (id < mCols * (mRows - 1))
            down = &mCells[id + mCols];

        mCells[id].setNeighbours(left, right, up, down);
    }
}

void CollisionGrid::clear()
{
    for (Cell& cell : mCells)
        cell.clear();
}

void CollisionGrid::addEntity(Entity* entity)
{
    mCells[getIdForPosition(entity->position)].addEntity(entity);
}

Cell::Container CollisionGrid::getNearbyEntities(Entity* entity)
{
    return mCells[getIdForPosition(entity->position)].getNearbyEntities();
}

int CollisionGrid::getIdForPosition(const sf::Vector2f position)
{
    return int(floor(position.x / mCellSize) + floor(position.y / mCellSize) * mCols);
}

```

# Answer
An option that is fairly prevalent in game development is to make use of a dirty flag or dirty list. Assuming you must delay the update of your grid and can't just do it when an object moves, this is the most efficient option you'll have.

Whenever an object moves, add it to the dirty list if its dirty flag is not already set. When it's time to update the grid, iterate over only the dirty list and do any logic with them as appropriate. Remember that two stationary objects cannot have their collision state change, so you only need to check for collisions between a dirty object and the others in its local area and you only need to update the grid for dirty objects. Clear the object's dirty flag after updating it. After the dirty list is updated, clear it. The result is that objects that are not moving incur zero overhead and all the moving objects can have any movement/collision logic executed in one batch, which tends to be faster.

Note that the dirty "list" does not have to be a linked list. The usual option I fall back to is an unsorted array/vector of pointers or handle IDs. You need only the collection of objects that have changed with no particular order, so pick the most efficient data structure you can for storing that collection.
> 1 votes

# Answer
I don't see why you can't have a linked list of all dynamic objects. This way all you need to do is re-insert all dynamic objects into the grid each frame. When you create a physics object you should be able to specify whether it is static or dynamic. This way you can have two separate lists to iterate over dynamic or static objects.

If you want the best performance you should consider using an intrusively linked list, so that you don't do any separate allocations of linked list nodes.
> 0 votes

---
Tags: c++, collision-detection
---


# Question
Title: Why is XmlSerializer adding junk to the end of my file?
I'm making a game and I am serializing the save game data. The data is simply a few lists of bools, ints and floats.

But about 50% of the time I get an error when the data tries to save or load that says "There is an error in XML document." The error is always located at the end of the file, even after it has changed size or I have added other variables.

It appears that very last part of the XML data is getting copied twice. The last line of the XML should read:

```
</LevelStats>

```

But when an error occurs it often reads

```
</LevelStats>>

```

Or

```
</LevelStats>tats>

```

Or some other small part of the last line duplicated.

Here is the class I am serializing:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using Microsoft.Xna.Framework.Storage;
using System.IO;

namespace Jetpack.Classes
{
    [Serializable]
    public struct LevelStats
    {
        // Player Bests
        public List<float?> fTimeList;
        public List<int?> iScoreList;
        public List<int?> iFuelList;

        // Time
        public List<bool> bBronzeTimeList;
        public List<bool> bSilverTimeList;
        public List<bool> bGoldTimeList;

        // Score
        public List<bool> bBronzeScoreList;
        public List<bool> bSilverScoreList;
        public List<bool> bGoldScoreList;

        // Fuel
        public List<bool> bBronzeFuelList;
        public List<bool> bSilverFuelList;
        public List<bool> bGoldFuelList;

        // Level Complete
        public List<bool> bIsLevelComplete;
    }
}

```

And here are my methods for saving the loading the data:

```
region Save & Load Level Stats
    public static void SaveLevelStats(LevelStats levelStats, string filename)
    {
        // Get the path of the save game
        string fullpath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename);

        // Open the file, creating it if necessary
        FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);
        try
        {
            // Convert the object to XML data and put it in the stream
            XmlSerializer serializer = new XmlSerializer(typeof(LevelStats));
            serializer.Serialize(stream, levelStats);
        }
        finally
        {
            // Close the file
            stream.Close();
        }
    }

    public static LevelStats LoadLevelStats(string filename)
    {
        LevelStats levelStats;

        // Get the path of the save game
        string fullpath = System.IO.Path.Combine((Directory.GetCurrentDirectory()), filename);

        // Open the file
        FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate,
        FileAccess.Read);
        try
        {
            // Read the data from the file
            XmlSerializer serializer = new XmlSerializer(typeof(LevelStats));
            levelStats = (LevelStats)serializer.Deserialize(stream);
        }
        finally
        {
            // Close the file
            stream.Close();
        }

        return (levelStats);
    }

    #endregion

```

Why am I getting the error above?

# Answer
You're seeing bits of the previous version of the file. In your `SaveLevelStats` function, change your call to `File.Open` from

```
FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);

```

to

FileStream stream = File.Open(fullpath, FileMode.Create);

`FileMode.OpenOrCreate` does *not* cause truncation of the opened file. That is, when you open the file and it already exists, the existing data is left intact. The returned stream still points to the beginning of the file, however. So when you happen to write an XML state that is shorter than the previously-saved state, you get bits of the previous file left over.

To solve this, want to use a different version of the `FileMode` enumeration when you call `File.Open`: `Create`, which

> Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires `FileIOPermissionAccess.Write` permission. `FileMode.Create` is equivalent to requesting that if the file does not exist, use `CreateNew`; otherwise, use `Truncate`. If the file already exists but is a hidden file, an `UnauthorizedAccessException` exception is thrown.
> 5 votes

---
Tags: xna, c#, xml
---


# Question
Title: How can I render a wave effect like the one used in California Games' surfing mini-game?
Well, I'm trying to study XNA, and I'm trying to make a California Games-inspired surfing game.

I got the surfer guy done, and it's working very well but I don't have any idea on how I should draw the wave coming and animate it. If you don't remember what the game looks like, here it is. The wave I'm talking about is the one which is coming from the left at around the 00:40 mark:

# Answer
> 2 votes
The effect is pretty primitive by modern standards. Fundamentally, it looks like you can break the wave effect down into columns where each column is a simple sprite that is falling downward under the influence of a gravity-like force, leaving behind contrail-style sprites that are fixed in position.

The falling sprite for each column is a noisy water sprite:

The fixed contrail sprites, which don't move, are more stable-looking water reproductions:

The specific image used for each fixed sprite or the leading moving sprite can be adjusted based on that sprite's current vertical position. That's how you can get the curved appearance of the wave over time (there's a different angle to the leading, noisy sprite depending on how close the wave column is to the bottom of the screen.

You can't do this entirely in the sprite sheet, obviously, you'll have to write code for it. But once you get it working for a single column, you can simulate the full wave effect by having multiple columns, starting new ones as the wave advances across the screen. Roughly, they'd look like

```
12345
-----
||||/
|||/
++/

```

where 1-5 are different copies of the single column effect started at slightly different times.

---
Tags: animation, sprites
---


# Question
Title: When updating a mesh, does 'glBufferSubdata' belong in the update or render function?
When updating a mesh, does the `glBufferSubdata` call belong in the update function, or the render function?

I'm trying to organize my game appropriately. and knowing this would help me. This is my first game, and I want to structure it properly.

# Answer
It really depends on what the purpose of the `update` and `render` functions you wrote and are referring to are.

The purpose of `glBufferSubData` is to update, in whole or in part, the data stored in an OpenGL buffer object. It is *fundamentally* a rendering operation, and so it absolutely belongs in render code.

Consequently if you are asking if the function belongs in the "update-the-game-logic" function called `update` or the "render the mesh" function called `render`, the answer is the latter. In this case you're talking about the separation of game state and specific gameplay logic from the act of rendering, which is generally a good separation, and should be enforced (if that is what your `update` is doing, it shouldn't be part of the `mesh` class at all because that is breaking that separation).

However if your `update` function *is* a render-specific update (for example, one that applies animation data to a mesh in some form, or one that pushes through new values for time-based shader parameters), then it is probably a reasonable approach to have your `glBufferSubData` call in *that* function rather than `render`, because fundamentally the call is about updating render information. This approach also makes it a little more obvious that you could update a mesh once to make it current, and then render it multiple times and helps keep that behavior separation in place, reducing the length of the `render` method which might otherwise need to have some lazy-evaluation checks so you didn't needlessly call `glBufferSubData` more times than you wanted to.
> 1 votes

---
Tags: rendering, game-loop
---


# Question
Title: How can I make a 32-bit render target with a 16-bit alpha channel in Direct3D?
I want to create a render target that is 32-bit, with 16 bits each for alpha and luminance. The closest surface formats I can find in the DirectX SDK are:

```
D3DFMT_A8L8    // 16-bit, 8 bits each for alpha and luminance.
D3DFMT_G16R16F // 32-bit float, 16 bits for red and 16 bits for green.

```

But I don't think either of these will work, since `D3DFMT_A8L8` doesn't have the precision and `D3DFMT_G16R16F` doesn't have an alpha channel (I need a separate blend state for alpha).

How can I create a render target that allows a separate blend state for luminance and alpha, with 16-bit precision on each channel, that doesn't exceed 32-bits per pixel?

# Answer
There are no formats with a 16-bit alpha channel except for `D3DFMT_A16B16G16R16F`.

Even if you could deal with encoding the luminance elsewhere, you'd also have to do similar tricks with alpha for your separate blend requirements, but the blend stage wouldn't understand those tricks and would produce unintelligible data.

I would suggest resorting, as suggested in the comments, to multiple render targets and a 'recombine' step.
> 1 votes

---
Tags: rendering, directx9, blending
---


# Question
Title: How can I render a model on top of another model regardless of their relative Z positions?
I was wondering if there's any way to render models over other 3D models regardless of their relative positions? Kind of like how it works in 2D graphics, you set a render order and it renders them based on that instead of taking the depth and figuring out which is in front of which.

# Answer
> 2 votes
Normally when we render 3D graphics, we make use of a depth buffer to achieve the proper visual appearance of solid objects in relation to each other regardless of the rendering order of said objects.

If, as in your case, you *do not* want this behavior, simply disable it somewhere in your initialization code. Do this by creating a new state object that controls the depth and stencil buffers and setting the appropriate member to `false`, then assign your state object to the graphics deviceenter link description here:

```
var state = new DepthStencilState();
state.DepthBufferEnable = false;

GraphicsDevice.DepthStencilState = state;

```

After the `GraphicsDevice.DepthStencilState = state` expression, objects will fully draw in the order in which you submit them for rendering, allowing you to draw objects over others regardless of their actual position in the world.

If you only want to do this for some subset of your objects, draw the world normally first, then set the depth-stencil state accordingly (make sure to reset it to a one that enables the depth buffer before you draw again for the next frame, and also make sure that you always create the state objects in your initialization code -- don't create them every frame, as that is expensive and wasteful).

# Answer
> 1 votes
You can do a two pass rendering. First pass you render the models that you want in the back. Then in the second pass instead of clearing the screen to redraw the frame, you only render the objects that you want to draw over the other models. That way the models in the second pass will draw over whatever was previously drawn.

# Answer
> 1 votes
Just to add to illeyezur's answer - to make this work, you will also need to clear the depth buffer in between drawing the two objects. This will let you keep depth testing enabled, so objects don't draw all over themselves and look awful, but will make sure that the object drawn second will always win in a depth test against the object drawn first.

So the procedure is:

1. Draw object you want to always appear behind.
2. Clear depthbuffer to `1` (the maximum depth value).
3. Draw second object, which will always appear on top.

Here, depth testing should be enabled throughout.

# Answer
> 0 votes
If you enable the depth buffer, you should use it well. Draw the stuff in the front, so those pixels behind don't need to be drawn.

---
Tags: xna, models
---


# Question
Title: Why would anti-aliasing work for the debug runtime but not the retail runtime?
I'm experimenting with setting various graphical settings in my Direct3D9 application, and I'm currently facing a curious problem with anti-aliasing. When running under the debug runtime, AA works as expected, and I don't have any errors or warnings. But when running under the retail runtime, the image isn't anti-aliased at all. I don't get any errors, the device creates and executes just fine.

As I honestly have little idea where the problem is, I will simply give a relatively high-level overview of the architecture involved, rather than specific problematic code. Simply put, I render my 3D content to a texture, which I then render to the back buffer.

Why would this be?

# Answer
Anti-aliasing is one of those things GPU vendors like to add explicit controls for in their drivers and control panels. Typically the options in these control panels can be used to override an application's requests to D3D for things like anti-aliasing support, and so on, and typically only work for retail runtimes.

It is consequently possible that the control panel for your GPU drivers has a setting (which is active, either by default or because you toggled it willingly or not) to disable AA.
> 2 votes

---
Tags: c++, directx9
---


# Question
Title: Is there any reason not to make all my components a single class?
What would be the downside to using a generic all-encompassing `Component` class versus specific classes (`PositionComponent`, `InputComponent`, et cetera) for each component in an entity/component system?

By 'generic' I mean:

```
class Component {
  String name; // component name, like "position"
  Map<Key, Object> attribs; // Attributes like "x" and "y" stored here.
}

```

Where a 'specific' component might be:

```
class PositionComponent {
  int x, y;
}

```

I feel like creating a separate class for each component means tons of 3-5 line classes in my code-base.

# Answer
There are a few things to watch out for in the "generic" component approach you propose:

* It means that a component is pure data, and cannot have any behavior unless you start doing things like allowing behavior objects (function pointers, or what-have-you) to be stored in the `attribs` member or in a similar member. This is a valid possible approach for an ECS, but not all ECS's choose the "component is pure data" model, and it's certainly not the *only* approach.
* The generic component stores all attributes in a dictionary; this means string (or some kind of key) lookups to recover data, boxing, and non-contiguous storage. The associative container also has storage overhead. All of these have performance impacts. You are also abandoning type-safety.
* Storage of the name as a string (rather than being able to intuit it from the type of the component) also means extra overhead.

Personally, I've never seen a "generic component" like you proposed out in the wild for anything *real*. It seems like a terribly poor choice, if for no other reason than when you have generalized the component so much you might as well reduce the overhead by making the *entity* the thing that stores all those properties, and namespace them:

```
class Entity {
  Dictionary<string, object> components;
}

// ...

var entity = new Entity();
entity.components.Add("Position.X", 1.0f);
entity.components.Add("Position.Y", 2.0f);
entity.components.Add("Position.Z", 3.0f);
entity.components.Add("RigidBody.Mass", 100.0f);
entity.components.Add("Killable.HP", 15.0f);

```

(But I still don't recommend it.)
> 6 votes

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


title: Premultiplied Alpha And Alpha Testing

text:
# Question
Title: Premultiplied Alpha And Alpha Testing
I have a shader that is supposed to work with either alpha blending or alpha testing, but the color values being passed in are premultiplied alpha values.

Is there an easy/standard way to have it produce the "correct" results for both alpha blending and alpha testing when using premultiplied alpha?

For example, if the final result of my shader is `RGBA(1,0,0,0.75)` straight alpha and therefore `RGBA(0.75,0,0,0.75)` premultiplied alpha, the result should be remain `RGBA(1,0,0,0.75)` when alpha testing.

Perhaps one option is "dividing out" the alpha channel if we are alpha testing, i.e. divide the `R` by `A` above so that we get `0.75/0.75 = 1.0`, our original red value. But this becomes non-deterministic when the alpha goes to 0.

Maybe I can clarify with an example:

Say the back buffer is `RGBA(1,1,1,1)`, and i am rendering with a partially transparent green color `RGBA(0,1,0,0.75)` (straight alpha). The color is passed in as premultiplied alpha as `RGBA(0,0.75,0,0.75)`. When alpha *blending*, i blend using one + invsrcalpha and get a final color of `RGBA(0.25,1,0.25,1)`. So my green channel stays at 100%, because the back buffer had green at 100%, and so did my original green color, so no way to get less than 100% on the green channel.

When Alpha *testing*, there is no blending going on. Instead, my green color will be rendered straight to the back buffer as `RGBA(0,0.75,0,1)`. But the color I wanted was `RGBA(0,1,0,1)`.

# Answer
> 2 votes
Depending on the shader language/version you're using, you can use conditionals in your shader program to cover the 100% transparent case explicitly.

Alpha testing really seems like it should be like a distinct shader from alpha blending. It doesn't seem like you can use it with premultiplied alpha, since the equations for alpha testing involve a conditional, and can't be expressed with Porter-Duff operations.

---
Tags: shaders, fragment-shader, blending, alpha
---


# Question
Title: How do I move an existing display object behind another in Corona Lua?
If I have two existing display objects in Corona, lets say `do1` and `do2`. Assume `do1` is drawn first then `do2`, so `do2` will be on top.

Is there a way to say "put `do2` behind `do1`" in corona Lua? If yes can you give me an example?

# Answer
If `do1` and `do2` are in a display group they appear in the order you insert them as:

```
local group = display.newGroup()
group:insert(do1)
group:insert(do2)

```

Groups are also numerically indexed and the objects are in display order based on the index:

```
assert(group[1] == do1) -- do1 is on the bottom
assert(group[2] == do2) -- do2 is on the top (front)

```

If you happen to add your items out of order, you can move another item to the top in a number of ways:

```
local group = display.newGroup()
group:insert(do2) -- do2 is on the bottom
group:insert(do1) -- do1 is on the top (front)

-- Move do2 to front by re-inserting it - only one instance will exist in group
group:insert(do2)

assert(group[1] == do1) -- do1 is on the bottom
assert(group[2] == do2) -- do2 is on the top (front)

-- Move do2 to the front

do2:toFront()

assert(group[1] == do1) -- do1 is on the bottom
assert(group[2] == do2) -- do2 is on the top (front)

-- Move do2 to the back

do2:toBack()

assert(group[1] == do2) -- do2 is on the bottom
assert(group[2] == do1) -- do1 is on the top (front)

```

See also toFront() and toBack().

You an only put items in the front or back. As far as I know there's no way to arbitrarily place items. You can however maintain display order in another list and insert them based on that order.
> 3 votes

# Answer
If you don't need organization and don't need to change the display order later on, you can just do:

```
do2:toBack()

```

Or:

```
do1:toFront()

```

Now, if you want to maintain them later on, then put both do1 and do2 into a display group:

```
doGroup = display.newGroup()
doGroup:insert(do2)
doGroup:insert(do1)

```

The fact that do1 was inserted last means it will now appear at the top. Also, a display object such as do1 or do2 can only be in **one** display group at any time, so you have effectively taken them away from the default display "stage" (which all display objects are placed by default) and moved them to a new one (the doGroup), which is now in another order.
> 2 votes

# Answer
Just Googled this question and since it's still unanswered, here's the way to do it for others in need:

```
local group = display.newGroup()
group:insert(do1)

for n = 1, group.numChildren do
    if group[n] == do1 then
        group:insert(n, do2) -- this puts do2 behind do1
        break
    end
end

```
> 0 votes

---
Tags: lua, corona-sdk
---


title: corona sdk scale images

text:
# Question
Title: corona sdk scale images
How to scale images to full screen on all devices, i want to use `%`

The method I've seen so far is to define pixels

`image_variable_name = display.newImage( "testimage.jpg", 100, 300 )`

I want to do something like

`image_variable_name = display.newImage( "testimage.jpg", 100%, 100% )`

But that won't work, I want something like fluid CSS, the image will maintain the size no matter what is the size of the screen. Is it possible?

# Answer
> 2 votes
Try using `newImageRect()` instead of `newImage()`

```
image_variable_name = display.newImageRect("testimage.jpg", display.contentWidth, display.contentHeight)
--then you have to center it:
image_variable_name.x = display.contentWidth / 2
image_variable_name.y = display.contentHeight / 2

```

# Answer
> 1 votes
Actually Corona uses feature called dynamic scaling so it let you working within same virtual size - 320х480. You can even have different assets for different scale factors.

# Answer
> 1 votes
Use display.newImageRect(), except unlike display.newImage(), you now have to enter the width and height of the image you are feeding in (the actual file). This will now scale automatically.

Also, if you ever switch to landscape mode for your default orientation, make sure your config.lua still has the fields width and height as if you were in portrait mode. Its a weird gotcha.

Here's how I present a background picture which takes up the full screen of a landscape mode 1280 x 720 display (Galaxy S3):

```
menuBg = display.newImageRect( "images/bg.png", 1280, 720 )
menuBg:setReferencePoint( display.CenterLeftReferencePoint )
menuBg.x = 0
menuBg.y = display.contentHeight/2

```

Setting the reference point is of personal preference, so play with that yourself.

---
Tags: lua, image, corona-sdk
---