# Question
Title: Logic level representation that distinguishes "<<under>> and <<above>> the bridge"
I have an **logic** level/map representation for a 3D game that uses `vector<Area>` where:

```
class Area{
    vector<Point2D> bounding; //determines the shape of the Area, its borders
    //bounding of Area is like borders of country
    //(it's easy to test if something is inside area)

    vector<Obstacle> obstacles; //general type for all static objects inside this Area
    //each Obstacle has boundingBox (center, halfSize, rotation)

    vector<Dynamic> dynamicObjects; //same as obstacles, but the use of separated vector
    //for dynamic objects helps with few things

    Player * player = 0; //like Obstacle, but it has special treatment

    vector<Area*> connectedAreas; //I won't went deeper into how Areas are connected.
    //For simplify, let's assume we are working on one Area.
    //Or that when Player leaves Area, all connectedAreas start a test if he entered
    //one of them (it's not the case, but work fine for purposes of that example).
    ...
};

```

It's quite simple and very low memory-consuming representation for large areas (grid representation would grow and grow with the size of area). I also find it quite good when it comes to some AI algorithms that my game uses. I don't have too advanced collisions in my game (so I don't need to care about them in the level representation). So generally, **I'm happy with that representation.**

**Still, I have one problem:** sometimes some parts of the map have "height-levels" - e.g. bridge: you can be either under the bridge or above it (and you can go above only from certain fragments of map). **How can I represent that?**

For caves or multi-floor buildings I can just use `vector<Area>` instead of single `Area`/`Area`'s fragment. That `vector<Area>` could hold separated `Area` for each floor.

But when the mesh has kind of "smooth" transitions between levels (bridges, some parts of mountains and any non-separable fragments of map) - **it doesn't looks like good solution anymore**.

For example, here player is able to go either under the tree or above the trunk:

P.s. **I am not asking for the graphic representation.** I've separated the game logic and graphic engine as much as possible. The 3D engine uses triangles of course, with much more details then game logic need or want (less data =\> faster processing).

# Answer
> 1 votes
In my online-game that I'm tinkering on as a hobby, I plan to split the map up into tiles that have only a 2D coordinate inside each tile. The vertical coordinate for a player or NPC inside its particular tile-cube will then simply be decided by the ground level underneath it. Since each tile has arbitrary connections to other tiles in 4 directions, stairs would still be possible to make. Just create a tile with the stair model (blue) at its end:

The player will seem to walk up the stairs because the ground level rises. If we now connect the left edge of the tile to the tile one level up, the user will easily walk up one level. The only downside of this approach is that a character won’t be able to hide under the stairs.

However, if your tiles aren't very tall (E.g. half the height of a typical character), you can have another tile for the area below, that is connected to the other tiles around the stairs, but not the stairs, and thus is drawn and accessible as if it was below. The stairs would be forced to a certain thickness, but apart from that you could have many levels.

Also, your 3D model would not need to include the lower part of the wedge, so it could *look* like you can walk directly below, while your character's head is just sticking out the top of its tile. I.e. in the above picture, you have the bottom level (white/blue) then the middle level (red) and then one flat tile from the top (green). If you e.g. connect the red tile to the surrounding white tiles, a player could fall off the stairs. If you don't connect them at all, you'd have an invisible wall.

Another advantage of using such tiles is that they can be used for simple collision testing. You can just block an entire tile from being stood on.

# Answer
> 1 votes
I'm struggling to understand what you're asking, but I'll take a shot at it. I'm assuming what you're talking about is an "area graph" or "zone graph", a concept for AI. In an area graph, parts of the map are linked logically in a sparse graph to make it easier for AI to understand what's going on. If that's the case, why not just add a 3rd coordinate to your areas?

```
class Area{
    vector<BoundingBox3D > bounds;
    vector<Obstacle > obstacles;
    ...
};

```

Then "above the bridge" merely has a bounding box higher than "below the bridge". If you want something even more generic than bounding box you can do this:

```
class Area{
    vector<Shape3D > bounds;
    vector<Obstacle > obstacles;
    ...
};

```

Where "Shape3D" is a generic 3D shape. You can then logically link these things together in a graph.

# Answer
> 1 votes
Why make it any harder then it needs to be? Just add a boolean to the entity state right next to the 2D position.

Then during rendering you will need to offset when try depending on the tile, some logic will also depend on the true false value like line of sight calculation.

But you can mostly short circuit that if you assume the amount of object like that are rare in a level.

---
Tags: c++, game-mechanics, maps
---


# Question
Title: how to turn (or solidify) water or fuild into solid material (Renderring Effect)
i want to implement an effect like this. for example, let's assume the clay are made of particles. liquids of clay flows for a while, then it becomes dry and rest.finally those particles becomes only one polygon, "dry clay". so i ask your disciplined gamedev guys, if you were me, how did you somehow implement this? BTW, this effect was a bit like mobile game , call "where's my water".

EDIT: sorry for my bad english. i've try to describe this question more detailed.. btw, a solution comes into my mind is use convex-hull-algorithm to outline the "dry clay", then triangulating the only one polygon into mesh, and using shader does smooth transition to implement fluid(or something else ) to simulate drying process for a while.

# Answer
> 0 votes
Personally, I would pass the array of liquid, free flowing particles into an array of inter connected, rigidly attached particles.

Basically, I am saying to take the hint of your physics code, that let's you know when a particle's rigid body went to sleep by having its velocity reach or approach 0 for enough time. Use this information to weld particles together as they stack by themselves.

Now, depending on your processing power available, you could: 1) Use a joint to attach touching particles, making them stick to each other up until a point where all particles are together, making the fluid not so fluid anymore. 2) Just remove the particle from the simulation, counting it as solid forever. As more particles go to "sleep", you continuously build a mesh to render instead of the particles. In the end you have no more particles but only a mesh / texture with the static fluid representation.

Depending on whether the solid can go back to a fluid, you'll have to keep the particle information alive, otherwise you can optimize by losing unnecessary data.

I am not 100% sure if I understood the question as a whole, but still, while I tried to explain how to solidify independent particles as far as physics would go, on the rendering side I would suggest to:

1) If using all particle information, do some kind of volume splatting (I think I got the name right? ), by rendering all particles as some kind of blob into a render texture. Then, you blur and grow a bit these hard edges particles so they overlap each other, and finally apply a filter that detects where there is color above a threshold, count it as a pixel inside the fluid, otherwise exclude it. This gives you a nice smooth shape for the fluid with no empty space in the middle, usually. You can then color it in different ways, but that depends on the material and your game graphical style. Then just render your fluid texture to the main level, and apply clipping if you need to make hard borders for the fluid, as to fit inside a container etc. Please someone correct me if I said something wrong here.

2) Otherwise just render the generated mesh, with or without similar technique as above.

Please provide more information in the question if other people also find it a bit vague. Hope this helps.

---
Tags: glsl, post-processing, computational-geometry
---


# Question
Title: How to compute point in view space from depth?
I am trying to implement do some screen space rendering but after looking over the web I still don't find answers to some doubts.

First, I need to compute the point in **view space** from a value in the depth buffer.

1. View-space means the camera-space or the clip-space?

I also found that, inverting the projection transformation I can get a point from the depth with a formula like

P(x,y) = \[(2x/Vx-1.0)/Fx , (2y/Vy-1.0)/Fy , 1\] * z(x,y)

where **Vx/Vy** are the dimensions of the viewport and **Fx/Fy** are the focal lengths

2. I don't understand where does this formula comes from, if I have it correctly the perspective projection formula is different. Can someone explain me this?
3. A point in view-space is a 3D-point, but why is the third coordinate 1?

# Answer
> 5 votes
1: camera space, like Andon said.

2: the projection matrix contains those Fx,Fy values (f and f/aspect) at cells \[0\]\[0\] and \[1\]\[1\] see https://www.opengl.org/sdk/docs/man2/xhtml/gluPerspective.xml

2x/Vx-1.0 is to convert from screen pixel coordinates which are from (0, 0) to (WIDTH, HEIGHT) to 3D projected coordinates that are from -1 to 1.

3: the "real" formula is

```
P(x,y) = [(2x/Vx-1.0)/Fx * z(x,y), (2y/Vy-1.0)/Fy * z(x,y), z(x,y)]

```

Because the x,y coordinates are divided by z when projected to the screen, you need to multiply by z to retrieve the 3D position.

Putting 1 as the 3rd value and multiplying the whole vector by z is shorter to type.

if I remember correctly, with x and y being the -1 to 1 screen coordinates, z being the depth buffer value:

```
vec4 temp = vec4(screen_x, screen_y, depth_buffer_value, 1);
temp *= projection_inverse;
vec3 camera_space = temp.xyz / temp.w;
vec3 world_space = camera_space * view_inverse; // if needed

```

depending on glDepthRange (or Direct3D equivalent) you might need to adjust depth\_buffer\_value if you changed the range and/or how the depth buffer values are sampled.

---
Tags: opengl, projection, depth-buffer
---


# Question
Title: How does Vector3.Angle compute the resulting angle?
I don't understand the concept of `Vector3.Angle` in Unity.

Can someone please explain in detail how it computes the angle? From which two points is the angle measured? It would also be really awesome if you could provide some diagrams for me understand it more, visually.

# Answer
> 3 votes
There is some confusion as to what the parameters for `Vector3.Angle()` are. This function takes two `Vector3` values. The documentation list them as `Angle(Vector3 from, Vector3 to)`, which I think the confusion is coming from. It can be read as (and it should be) **from** here **to** there. If you are thinking of these parameters as points, this from here to there idea gives you a line. However, if you consider the parameters to be vectors, then what you are looking at is an angle. This is illustrated by the purple arc.

# Answer
> 2 votes
The lines you're looking for are those you get if you connect the point `(0, 0, 0)` with each of the two vectors. So, assuming that you have a vector `from` with coordinates `(x1,y1,z1)` and a second vector `to` with coordinates `(x2,y2,z2)` then `Vector3.Angle(from, to)` returns the angle between the red and the blue line:

---
Tags: unity
---


title: Why are normal maps predominantly blue?

text:
# Question
Title: Why are normal maps predominantly blue?
Why normal maps are predominantly blue instead of a random color?

I guess normal vectors of a 3D object can point in every direction, like:

```
(1.0, 0.1, 0.5), (0.1, -0.5, 0.3), (-0.51, 0.46, -1.0) ...

```

# Answer
> 73 votes
There are two types of normal maps commonly used in game development. The way you are thinking they should work is the way one type works (model-space normal maps), but most games use another type (tangent-space normal maps) which is why you associate mostly-blue textures with normal maps.

With **model-space normal maps**, each channel encodes the precise value of the normal using the same coordinate system as the vertices of the model it's used with. This means different parts of the normal map will have different hues, but pixels near each other will usually have similar colors. An example of a model-space normal map appears above (source).

**Tangent-space normal maps** are usually light blue. This type of map defines normals in a coordinate space unique to each pixel's position on the surface of the mesh. It uses the (interpolated) vertex normal as the Z axis, and two other orthogonal vectors, called the tangent and bitangent, as the X and Y axes. Essentially, you can think of the normals in the map as an "offset" from the normal for that pixel calculated by interpolating the vertex normals. The tangent and bitangent vectors are also interpolated from vertex data, and determine which direction on the mesh corresponds to "up" and "left" in the normal map. The image provided in the question provides an excellent example of what a typical tangent-space normal map looks like, so I won't provide another example here.

The components of a normal normally (no pun intended) range from `[-1, 1]`. But components of a color in an image range from `[0, 1]` (or `[0, 255]` but usually they're normalized to `[0, 1]`). So normals are scaled and offset such that the normal `(0, 0, 1)` becomes the color `(0.5, 0.5, 1)`. This is the light blue color you see in normal maps, and it indicates no deviation from the interpolated vertex normal when using tangent-space normals.

The reason tangent-space normals are preferred over model-space normals is due to the fact that they are easier to create, and can be used for multiple meshes. Additionally, if used with an animated mesh, tangent-space normals are always used, because the normals are constantly changing.

# Answer
> 8 votes
The normal map mostly points outward from a surface. Assuming you go with the usual mapping of the Z component of the XYZ normal vectors being the "depth" direction and an that mapping to the B component of the RGB color space, you'll end up with most normal vectors being primarily blue.

If the texture were, say, red, then that would mean that the normal map is a surface that's mostly pointing off to the right. You can see that feature on your sample image as the right-most edge of the bumps have a reddish tint to them.

A complete surface of a reddish color wouldn't make any sense. That would indicate a surface that is entirely facing off towards the right. That would just be modeled with geometry, not part of a normal map.

---
Tags: graphics-programming, normals
---


# Question
Title: Joystick control for camera only works when button pressed
I'm trying to use a controller that has a joystick. I'd like to move the camera when the player moves the joystick. The joystick also has a button. So far I'm only seeing the camera move when the button is pressed. How can I get the camera to move even when the button is not pressed?

I added the part that handles the movement, and yes I know that the method `GetButtonDown` is incorrect for what i'm asking to do, but I don't see any other functions that handles the joystick movements.

```
protected virtual void UpdateObject(  SixenseInput.Controller controller )
{

    z += 0.5f;
    if (controller.GetButtonDown (SixenseButtons.JOYSTICK)) {
        m_initialPosition += new Vector3(0.0f,0.0f,z);
        this.gameObject.transform.position = m_initialPosition;
    }
}

```

# Answer
You are literally getting the Joystick button state and only moving if it's pressed...

```
if (controller.GetButtonDown (SixenseButtons.JOYSTICK)) {

```

Just remove it. If you already know it's not correct then take it out. No need to clutter.

```
protected virtual void UpdateObject(  SixenseInput.Controller controller )
{
    z += 0.5f;
    m_initialPosition += new Vector3(0.0f,0.0f,z);
    this.gameObject.transform.position = m_initialPosition;
}

```

Then look for `controller.JoystickX` and/or `controller.JoystickY` \<- this will give you the values you need. It took 2 minutes to search in Google which gives me the impression you didn't, the API should be included with the download for the Unity Plugin - I'd highly recommend reading it.
> 1 votes

---
Tags: unity, controllers
---


title: LibGDX change screen after 2 seconds

text:
# Question
Title: LibGDX change screen after 2 seconds
Ive tried using a timer in the render method but that just crashes my game, so how do I change screens after a certain amount of time after rendering.

# Answer
> 5 votes
Track the elapsed time in your `Screen`, then when a limit is reach as the `Game` instance to swap to your next screen;

```
public class MyScreen extends ScreenAdapter {
  private final Game game;
  private float elapsed;

  public MyScreen(final Game game) {
    this.game = game;
  }

  public void render(float delta) {
    elapsed += delta;

    // Render or do whatever you do here

    if (elapsed > 2.0) {
      game.setScreen(new MyOtherScreen(game));
    }
  }
}

```

For this I am assuming you're using http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Game.html and http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/Screen.html.

---
Tags: libgdx
---


# Question
Title: How to gradually decrease opacity of model?
I have been searching for this matter for a long time and slowly I begin to think that this option is not available in XNA for Windows Phone.

I am trying to get a 3D-Model to be drawn at 50% opactity/transparency.

The most promising piece I found is following:

```
//1. Set the alpha blend mode for the graphics device with:

graphics.GraphicsDevice.RenderState.AlphaBlendEnable = true;
graphics.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha; // source rgb * source alpha
graphics.GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One; // don't modify source alpha
graphics.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha; // dest rgb * (255 - source alpha)
graphics.GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.InverseSourceAlpha; // dest alpha * (255 - source alpha)
graphics.GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add; // add source and dest results

//2. Set the alpha value in the BasicEffect for the model:
effect.Alpha = 0.5f; // Creates a 50% translucent object.

```

But GraphicsDevice.RenderState.AlphaBlendEnable isn't even available in XNA for Windows Phone.

So is there any way to achieve that effect?

# Answer
Considering the age of this question, you likely have already found an answer, but I thought I would share my approach either way.

Assuming your model has a convex shape, you can try pre-rendering the model's texture to a render target with a SpriteBatch, using the appropriate alpha value. Then apply that render target to your model. That way, you won't have to bother with RenderStates.

```
RenderTarget2D modelTargetTex; // assuming these are defined elsewhere
SpriteBatch spriteBatch;
// draw your model's texture to a render target, with a specific alpha value.
// put this at the start of your Draw() method
GraphicsDevice.SetRenderTarget(modelTargetTex);
GraphicsDevice.Clear(Color.Transparent); // so the alpha blending will work correctly
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
spriteBatch.Draw(originalModelTexture, Vector2.Zero, Color.White * yourAlphaValue);
spriteBatch.End();
GraphicsDevice.SetRenderTarget(null); // don't forget to unset the render target

```

Once that is done, you can simply assign the render target to your model (`basicEffect.Texture = modelTargetTex;`) through whatever method you use to draw them. This method would work best on convex models because a concave shape might show graphical artifacts when polys overlap.
> 1 votes

---
Tags: xna, c#, windows-phone-8
---


title: Acceleration based on current speed?

text:
# Question
Title: Acceleration based on current speed?
The faster an object goes, the slower it will accelerate, going from 0 to 50 takes a lot less time then going from 50 to 100,

How do I calculate that, though?

EDIT: Extra details,

This specific scenario is about a space ship, here is the code I'm using for giving it a constant acceleration, which I'd like to rewrite so that the faster it goes, the slower it accelerates.

EDIT2: Thanks to Sam Hocevar the code I showed was flawed, I've updated the code.

```
var dx = this.x - this.destination.x,
    dy = this.y - this.destination.y,
    r = Math.atan2(dx, dy) * -1,

this.speed += this.acc;
if(this.speed > this.maxSpeed){ this.speed == this.maxSpeed; }

this.x = Math.sin(r) * this.speed + this.x;
this.y = (Math.cos(r) * this.speed * -1) + this.y;

```

Old code.

~~```
this.sx += (this.destination.x > this.x) ? this.acc : -this.acc;
this.sy += (this.destination.y > this.y) ? this.acc : -this.acc;

if(this.sx > this.maxSpeed){ this.sx = this.maxSpeed; }
if(this.sx < -this.maxSpeed){ this.sx = -this.maxSpeed; }
if(this.sy > this.maxSpeed){ this.sy = this.maxSpeed; }
if(this.sy < -this.maxSpeed){ this.sy = -this.maxSpeed; }

this.x += this.sx;
this.y += this.sy;

```~~

# Answer
> 8 votes
You have an opposing force called "friction", which is proportional to speed. This is how objects falling in an atmosphere are modeled, for example.

If your impulse force is `F`, a constant, and you have a mass `m`, your acceleration is the constant

```
a = F/m

```

Let's call the friction force `Q`, and the acceleration caused by that `q`. We have that

```
Q = k*v

```

where `k` is a constant (that depends on several things, like material and surface and viscosity and whatnot, but you just choose a number that feels right), and `v` your current speed.

```
q = Q/m = k * v / m

```

The new speed `v'` will be the timestep times the total acceleration:

```
v' = v + dt * (a - q) = v + dt * (a - k/m * v)

```

The new position `x'` will be the timestep times the current speed:

```
x' = x + v * dt

```

P.S. In your code up there, you just have to modify acc before the first computation, subtracting the product of your current speed and some small constant.

# Answer
> 2 votes
I believe that the proper way to do this is to add a friction force. A force can simply divided by the object's mass to get an acceleration. The simplest variant is a force proportional to the speed or the square of the speed, in a direction opposite to the velocity.

Also your acceleration should have the direction of your ship: as of now, the ship is only accelerating at 45-degree angles which is somewhat weird.

The integration of the position is not very accurate either; look for "Velocity Verlet" for a way to improve accuracy.

Finally, merely adding an acceleration to a velocity does not make physical sense; you probably have a hidden timestep somewhere, it would be better to include it in the calculations.

```
/* Compute the wanted direction of the ship */
float dx = (this.destination.x - this.x);
float dy = (this.destination.y - this.y);
float d = sqrtf(dx * dx + dy * dy);
dx /= d; dy /= d; /* FIXME: check for division by zero here! */

/* Accelerate towards the destination */
this.sx += this.acc * timestep * dx;
this.sy += this.acc * timestep * dy;

/* Apply friction force with coefficients K1 and K2 */
/* FIXME: ensure that velocity does not change sign due to high friction */
this.sx = (-K1 -K2 * abs(this.sx)) * this.sx * timestep;
this.sy = (-K1 -K2 * abs(this.sy)) * this.sy * timestep;

/* Integrate position */
this.x += this.sx * timestep;
this.y += this.sy * timestep;

```

Now in order to limit the final velocity you just need to tweak the K1 and K2 values.

# Answer
> 1 votes
I think some of the answers here are missing something. I think what you really want is *controls* and not *physics*. Let me explain. Control theory explores the mathematics of systems that can *sense* a value, and *control* themselves to reach a target value. Examples of this include climate control systems, anti-lock breaking systems in cars, robots, and yes even spacecraft in space.

*Physics* is what happens to the system due to the laws of nature. In space, there is no friction, and no forces acting on your ship besides the engine so the physical system is very simple:

```
// Newton's third law
Acceleration = Force / Mass;

// Newton's first law
Velocity' = Velocity + Acceleration * dt
Position' = Position + Velocity * dt

```

But you additionally have two *Control Inputs* that influence the system. That is, the angle and force of the ship's engine!

```
// Engine
Force = Engine_Thrust * [Cos(Engine_Angle), Sin(Engine_Angle)];

```

So the question you should be asking is: *what angle should the engine be pointing at, and how much force should it apply?*

That is, we want to find a *Control Law*, which is a function that determines the engine angles from the position, the velocity and some target:

```
// Sets the engine thrust and angle based on some target
void ControlLaw(Vector position, Vector velocity, Vector target)
{
    Engine_Thrust = ?
    Engine_Angle = ?
}

```

Right now, you already have a simple control law:

```
// Sets the engine thrust and angle based on some target
void BangBangControl(Vector position, Vector velocity, Vector target)
{
    Engine_Angle = atan2(target.x - position.x, target.y - position.y);
    Engine_Thrust = 1.0;
}

```

What your control law is saying is * Always point the engine toward the target, at full thrust"\*. As you can imagine, what this will cause your space ship to do over time is just to accelerate as quickly as possible toward the target, overshoot the target, and then oscillate around it. What you've invented is something called "Bang Bang Control." What you said you want instead is something more useful: you want the space ship to move toward the target, slow down on approach to the target, and then stop when it reaches the target. To do this, I recommend something called PD Control. This kind of controller applies more thrust when further away from the object, and less thrust when closer. It also applies thrust to resist the motion of the spacecraft. It's actually very simple:

```
// Sets the engine thrust and angle based on some target.
void PDControl(Vector position, Vector velocity, Vector target)
{
    // The current error
    Vector error = target - position;

    // The simple PD control law represented as a 2D vector.
    // KP and KD are arbitrary constants. KP should be positive,
    // while KD should be negative.
    Vector output = KP * error + KD * velocity;

    // Set the angle and thrust to mirror the output vector
    Engine_Angle = atan2(output.x, output.y);
    Engine_Thrust = output.Length();

}

```

PD control will cause your ship to move smoothly toward a target and stop. By tuning KP (the proportional constant) and KD (the damping constant), the movement can be made to oscillate, move quickly, or move slowly. Basically, the PD controller is simulating a spring with friction. The great thing about it is that no matter what physics you throw at the system (say if you add gravity, or collisions with obstacles), the PD controller will still drive the space ship toward the target.

# Answer
> 0 votes
*Later edit*

```
var dx = this.x - this.destination.x,
dy = this.y - this.destination.y,
r = Math.atan2(dx, dy) * -1,

// when the speed approaches maxspeed, the acceleration of the ship is just a fraction
//of its maximum allowed acceleration - assumed to be this.acc
var fractionalAcc = (1 - Math.Pow((this.speed/this.maxSpeed),2)) * this.acc;

this.speed += fractionalAcc;
if(this.speed > this.maxSpeed){ this.speed == this.maxSpeed; }

this.x = Math.sin(r) * this.speed + this.x;
this.y = (Math.cos(r) * this.speed * -1) + this.y;

```

---
Tags: mathematics, algorithm, simulations
---


# Question
Title: Alpha blending sometimes gives the wrong color?
I've got a method for alpha blending:

```
public static int alphaBlend(int c1, int c2) {
        int a1 = (c1 & 0xff000000) >>> 24;

        int r1 = (c1 & 0x00ff0000) >> 16;
        int r2 = (c2 & 0x00ff0000) >> 16;

        int g1 = (c1 & 0x0000ff00) >> 8;
        int g2 = (c2 & 0x0000ff00) >> 8;

        int b1 = (c1 & 0x000000ff);
        int b2 = (c2 & 0x000000ff);

        float src_alpha = ((float)a1) / 255.0f;

        int red   = (int) ((r1 * src_alpha) + (r2 * (1.0f - src_alpha)));
        int green = (int) ((g1 * src_alpha) + (g2 * (1.0f - src_alpha)));
        int blue  = (int) ((b1 * src_alpha) + (b2 * (1.0f - src_alpha)));

        return (a1 << 24) | (red << 16) | (green << 8) | blue;
    }

```

But sometimes this gives the wrong color (I guess because I don't use the second color's alpha). Could anyone explain how to fix this?

# Answer
What do you mean by "wrong"?

Your first step could be to say clearly (to yourself, or in a unit test, or in this question) "I expected alphaBlend(something,something) to produce (something, preferably a number), but what I got was (something else)." Like, blended red and blue, expected purple, got mauve. Or whatever. Hex values would be clearer...

At a quick reading of the arithmetic, the color output looks correct, although the resulting alpha for a "source over" compositing operation is usually:

a-result = a1 + a2 - a1 * a2

http://en.wikipedia.org/wiki/Alpha\_compositing#Alpha\_blending
> 1 votes

---
Tags: alpha-blending
---


# Question
Title: How does one prevent homing missiles from orbiting their targets?
I am developing a 2D space game with no friction, and I am finding it very easy to make a homing missile orbit its target. I am curious about anti-orbiting strategies.

A simple example is a homing missile that simply accelerates directly toward its target. If that target were to move perpendicular to the missile's trajectory then stop, the missile's acceleration toward the target would not be enough to overcome it's own velocity, and the missile could be driven into orbit around the target, as depicted:

* In frame 1, the missile is heading straight for its target, no problems.
* In frame 2, the target has moved to a new position as demonstrated. The missile continues to accelerate directly toward the target (in red), while still moving toward where the target used to be (in black) due to its existing velocity.
* In frame 3, the missile's velocity continues to carry the missile around the side of the target (black) while the acceleration vector tries desperately to pull the missile toward the target.
* In frames 4 and beyond, the missile falls into a potentially stable orbit around the target and never reaches its goal. The black arrows indicate a velocity vector while the red lines indicate acceleration vectors at the same moment in time.

Considering that there is no friction in space, there is nothing to slow the velocity of the missile down and collapse the orbit. A possible solution would be to aim "behind" the target, and this would cause the orbit to close, but how is this done from a programming point of view?

How do I make a homing missile reach its target?

# Answer
First of all, you should make all calculations about what acceleration to apply in the *missile's* frame of reference (that's where the missile is stationary and everything else moves around it, also often called "object coordinates" or "local coordinates" in game engines, though in our case we want the velocity to be exactly zero as well).

The idea then is not to aim for the target, but to aim for the place where the target will be at the estimated time of impact. So the general algorithm looks like this:

1. Estimate how much time it will take for the missile to reach the target. If the target is flying directly at it (remember, the missile is *stationary*), it can be as simple as calculating *distance* / *speed*, in other cases it can be more complicated. If the target can try and evade you won't be able to make a perfect estimate anyway, so it's ok to not be very precise.
2. Assuming constant speed (1st degree estimate) or constant acceleration (2nd degree estimate) of the target, calculate where it will be at the estimated time above.
3. Calculate acceleration which will lead to the missile to be at roughly the same spot at the same time.
4. Re-project the acceleration back from the missile's frame of reference to the global one, use that.

The important part here is to get the time estimate in the rough ballpark, and to not forget the missile's acceleration capabilities while doing so. For example, a better estimate for "the target is straight ahead of us and flying in our direction" would be to solve the equation ..

*distance* = *speed* x *time* \+ 1/2 x *acceleration* x *time*2

... for *time* (use negative speed for objects flying straight *away* from the missile), with the solution you're looking for using the standard quadratic formula being ...

*time* = (√(*speed*2 \+ 2 x *acceleration* x *distance*) - *speed*) / *acceleration*

Adding additional parameters - drag, for example - quickly turns this into differential equations with no algebraic solutions. *This* is why rocket science is so hard.
> 51 votes

# Answer
@Martin Sojka already told you what to do. Instead of improving his response I want to propose you another simpler aproach: **DELOCK**

As I said in Projected trajectory of a vehicle?, objects with limited steering capabilities do "project" a couple of shadow cirles: two regions that can not be reached via direct steering (a torus and an hypertorus in higher dimensions).

When you see that you target is entering in one of such steering shadows, you can stop homing your target and keep another direction for a limited amount of time.

The delocking trigger can be computed easily by aproximating your tori with a (double) cone\*:

You have to simply compute the scalar product between your (normalized) direction vector and your target displacement vector ( **Target** \- **Object** /|**Target** \- **Object**| ).

As the scalar product goes to zero, your target direction becomes perpendicular to your direction leading to a circular trajectory\**. When the target falls into the cyan region you can invert your steering direction so you can put it outside the unreachable area and re-homing.

* To be honest this is not a cone... is another kind of ruled surface generated by (semi) revolution of two non parallel lines around an axis passing through the intersection and perpendicular to the bisector line; The projection on a 2D plane is the same as the double cone, but the rotation axis is perpendicular to the one that generates the cone.

\** That trajectory is unlikely to be circular nor elliptic or even closed. The chances are that the trajectory will follow a spirograph like path (an hypotrochoid) in 2D or even other monsters in 3 and up dimensions. You can not reach the center of such curves anyway and they look like circles so "circular" trajectory.
> 43 votes

# Answer
Your guidance system is built on the assumption that accelerating directly towards the target will eventually cause the objects to collide. Since that assumption is false, the guidance AI based on that assumption is likewise unsuccessful.

So stop accelerating *directly* towards the target. Add some logic to detect if the target's position is somewhat perpendicular to the direction of the missile's motion. If so, then the missile needs to accelerate towards the target, but also slow down its forward motion. So rather than going directly towards the target, it biases the direction of its acceleration so that the current speed in its direction of motion is slowed down.

Also, you'll need a trigger to make sure that you're not going too slow. So add some threshold speed such that, if you're below that threshold, you stop doing the biasing.

One last thing: no guidance system will be perfect. The reason missiles can intercept targets in real life is that targets move much slower than the missiles themselves, and the targets are not particularly nimble (relatively speaking). If your missiles are not going to be many times faster than the targets they chase, then they will miss a lot.
> 8 votes

# Answer
The most simplest and advanced method to use for this in games (and real life) is Proportional Navigation.

Under the Constant Bearing Decreasing Range (CBDR) logic, when two objects (missile and target) are traveling in same direction without change in sightline between each other, they *will* collide.

Sightline, or Line of Sight (LOS) is imaginary line between missile and the target -- the vector between missile position and target position. The rate of angular change of this LOS is the LOS Rotation Rate.

When LOS Rotation Rate becomes zero, then the sightline no longer changes -- the two objects are now on a collision course. Think of yourself as chasing someone whilst playing football/soccer. If you lead him in a way that his body looks "frozen" in your field of vision (sightline between you and him no longer change), you will collide with him as long as you maintain your running acceleration to keep his body appear frozen in your view.

Under Proportional Navigation (PN), missile accelerates "N" times faster than the LOS Rotation Rate. This will force the missile to lead the target until LOS Rotation Rate becomes zero -- that is, the missile and target appear frozen in state as sightline no longer changes -- they are now on collision course. The variable "N" is known as Navigation Constant (a constant multiplier).

Missile's guidance command should be given as follows:

Acceleration = Closing Velocity * N * LOS Rate

LOS Rate can be easily derived by measuring the LOS vector (target position - missile position), and storing its variable. The LOS vector from the new frame (LOS1) is subtracted by LOS vector from the old frame (LOS0) to generate a delta of LOS -- now you have a primitive LOS rotation rate.

To simplify Closing Velocity, you can just use the current LOS vector in its place, thus:

Acceleration = ( target\_pos - missile\_pos ) * LOS\_delta * N

N is the navigation constant -- in the real world, it is typically set between 3 to 5, but the actual workable figure in game is somewhat dependent upon the sampling rate at which you're deriving the LOS rate/delta. Try a random number (start from 3) and increase up to 1500, 2000, etc until you see desired leading effect in game. Note that higher the navigation constant, the faster the missile will react to LOS rate changes early on in the flight. If your homing rocket simulation model is somewhat realistic, excessive navigation constant could overload your missile's aerodynamic capability, so you should use a balanced number based on trial and error.
> 5 votes

# Answer
As the other answers by Martin and Nicol point out, you probably want to guide your missile not directly at the target, but in a way which will make it collide with the target later on. However, the method described by Martin is complicated and the one described by Nicol is inefficient.

A simpler way - but still pretty efficient - to guide a missile is by adjusting its angle according to the angle change between the missile and the target. On every tick you calculate the angle from the missile to the target, and compare it with the angle from the previous tick. The difference is the exact difference you want to make on the missile's angle. So if the angle was 0.77 in one tick and 0.75 in the next, you want to adjust the missile's angle by -0.02. This method is simple, and as long as the target is "in front" of the missile, it's very efficient in terms of route chosen. It also applies to any number of dimensions, not just in 2d.

Keep in mind, though:

* This method breaks if the missile and the target are in the exact same speed and travel in parallel. Well it still theoretically plots a collision course for the missile, it just takes infinite time :) in practice the missile should always be faster than the target, but if they have identical speed you need to add a corner case to identify whether they are parallel.
* The method breaks if the target and missile are flying on the exact same line but in opposite directions. That cannot really happen in the real world, but isn't too uncommon in a discrete game. You need to add a corner case check to the above algorithm to test for this.
* If your missile has limited turning capability, just make it do the maximum turn every time it needs to turn more than that. As long as the missile is far enough it will still work. If it's too close, see the last bullet.
* Remember to be lenient when checking collision. In the real world many missiles rely on their warhead to produce a "kill zone", so they only need to get close to the target, not actually collide with it.
* Finally, in practice the missile *may still miss*, which brings us back to your original question. I think a good way is to indeed disable homing for a few ticks, letting it achieve some distance, and then make it homing again. I think the method proposed by fxiii to identify dead zones is a great way to detect when you need to turn off homing.
> 4 votes

# Answer
A couple of simple options that have been found to be 'good enough' for games I've worked on in the past:

1) If the resolution of the scene you are looking at allows it, then the object can explode when it is Near the target (Which is how I believe most common day homing missiles actually work in any case). If your orbiting range is about twice the size of the object away then this will likely not work for you as it would just end up looking bad.

If your end goal in your solution is simply to make sure your missile hits the target, then I am all for just Making it hit the target. Again, this will just depend on how the solution looks.

2) If you find that your missile is at a right angle to your target, this could be the point where the lock 'breaks', and the missile just moves straight unless the target gets 'in front of' the missile again.

I always prefer simple solutions whenever possible. If you are making a game where the homing missile is just one of the weapons being used then you can likely get away with these as players are likely to fire off a salvo and then swap back to their constant engagement weapons as soon as possible. If you are making a missile simulation however, then clearly one of the other answers is the better choice.

Hope this helps.
> 1 votes

# Answer
As has been said you should aim the missile for where the target is expected to be when you get there rather than for where the target is right now. This will stop **MOST** missiles from going into orbit but an orbit is still possible if the target evades just right. This is a legitimate tactic used by aircraft pilots to dodge incoming missiles--since the missile is going much faster than you it will have a larger turning radius and a sharp jink at the right instant causes it to go on by. (Although you could still be at risk from a proximity detonation.)

Since we are dealing with a missile that can still track and still has thrust you get an orbit situation if the target evades into one of the zones that FxIII's post talks about.

However, I disagree with his solution to the problem. Instead, I would program the missiles thusly:

if the missile has been thrusting at 90 degrees to it's line of motion for 360 degrees of movement you are in orbit. Adjust the thrust to 120 degrees from the line of motion. The missile's orbit will widen as it's not turning as hard but the missile will also slow, thus allowing it to maneuver better. When the range to target opens to 1.25x the diameter of the dead zone (note that this diameter is based simply and only on the missile's speed, no complex calculation is required at runtime) the missile returns to it's normal tracking behavior.

Alternately, use dumber seeker heads--when the range to target ceases to count down you detonate.
> 0 votes

# Answer
I know this is an oldish question, but I think there is something that has been missed in the answers given so far. In the original question, the missile (or whatever) was told to accelerate towards the position of the target. Several answers pointed out that this was wrong, and you should accelerate towards where you think the target will be at some later time. This is better but still wrong.

What you really want to do is not **accelerate** towards the target but **move** towards the target. The way to think about this is to set your desired velocity pointed at the target (or a projection of the targets location) and then figure out what acceleration you could best apply (given whatever restrictions you have, i.e. a missile probably can't accelerated directly in reverse) to achieve your desired velocity (remembering that velocity is a vector).

Here is a worked example I implemented this morning, in my case for a player AI in a sports simulation game, where the player is trying to chase their opponent. The movement is governed by a standard 'kick-drift' model where accelerations are applied at the start of a timestep to update velocities and then objects drift at that velocity for the duration of the timestep.

I would post the derivation of this, but I've found there is no math markup supported on this site. Boo! You will just have to trust that this is the optimal solution, bearing in my that I have no restrictions on the acceleration direction, which is not the case for a missile type object, so that would require some extra constraints.

Code is in python, but should be readable with any language background. For simplicity, I assume each time step has a length of 1 and express the velocity and acceleration in appropriate units to reflect that.

```
self.x = # current x co-ordinate
self.y = # current y co-ordinate
self.angle = # current angle of motion
self.current_speed = # current magnitude of the velocity
self.acc # Maximum acceleration player can exert on themselves
target_x = # x co-ordinate of target position or projection of it
target_y = # y co-ordinate of target position or projection of it
vx = self.current_speed * math.cos(self.angle) # current velocity x component
vy = self.current_speed * math.sin(self.angle) # current velocity y component
# Find best direction to accelerate
acc_angle = math.atan2(self.x + vx - target_x,self.y + vy - target_y)

```

Note that the atan2(a,b) function computes the inverse tan of a/b, but ensures the angles sits in the correct quadrant of a circle, which requires knowing the sign of both a and b.

In my case, once I have the acceleration I apply that to update the velocity by

```
vx_new = vx + self.acc * math.cos(acc_angle)
vy_new = vy + self.acc * math.sin(acc_angle)
self.current_speed = math.sqrt( vx_new**2 + vy_new**2)
self.angle = math.atan2(vy_new,vx_new)

```

I also check the new speed against a player dependent max speed and cap it at that. In the case of a missile, car or something with a maximum turning rate (in degrees per tick) you could simply look at the current angle of motion versus the calculated ideal and if this change is greater than allowed, just change the angle by as much as possible towards the ideal.

For anyone interested in the derivation of this, I wrote down the distance between the player and target after the timstep, in terms of the initial position, velocity, acceleration rate and acceleration angle, then took the derivative with respect to the acceleration angle. Setting that to zero finds the minima of the player-target distance after the timestep as a function of the acceleration angle, which is exactly what we want to know. Interestingly, even though the acceleration rate was originally in the equations, it cancels out making the optimal direction independent of how much you are actually able to accelerate.
> 0 votes

# Answer
You are using a constant turn rate. That is exactly what is causing the nice perfectly circular orbit.

A more realistic approach for a guidance system would be to vary the turn rate with inversely target distance (less distance --\> more turn rate). This would give a spiral rather than orbit, and guarantee collision with a slower target.

It also gives a much more realistic flight path. The constant turn rate is unnaturally perfect. You can also add random variations to the turn rate to simulate turbulence. Again, much more realistic, and can actually avoid steady-state orbiting scenarios.

No need for partial equations.
> 0 votes

---
Tags: 2d, ai
---


title: Can state setting warnings be ignored?

text:
# Question
Title: Can state setting warnings be ignored?
If I am running DirectX 11 in debug mode (D3D11\_CREATE\_DEVICE\_DEBUG), I am constantly getting these warnings:

```
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets: Resource being set to OM DepthStencil is still bound on input! [ STATE_SETTING WARNING #9: DEVICE_OMSETRENDERTARGETS_HAZARD]
D3D11 WARNING: ID3D11DeviceContext::OMSetRenderTargets[AndUnorderedAccessViews]: Forcing PS shader resource slot 6 to NULL. [ STATE_SETTING WARNING #7: DEVICE_PSSETSHADERRESOURCES_HAZARD]

```

It is because I am setting a resource as a render target while it is currently bound to the PS. However, my rendering flow is set up such as it relies on the api to force the resource slot to null, and *it works*.

Is there any reason I should be bothered with these warnings or I can rely on the api to enforce this every time? I only tested on 2 GPU-s: Intel HD 3000 and Nvidia GT525m.

# Answer
> 1 votes
Ideally you should have no warnings, but depending on your application you may find a number of warnings tolerable or even desirable. In that case, you might consider suppressing the particular warning so you don't end up with noise in the output causing you to miss other warnings.

See Direct3D SDK Debug Layer Tricks for how to do this.

Note that you should never suppress **CORRUPTION** or **ERROR** output and just fix them.

---
Tags: directx11
---


# Question
Title: Why doesn't it seem to be any development in the field of 3D VR gear, especially with regard to gaming?
I remember that way back around 1995, there was this big craze with VR in the media, a whole bunch of (mostly mediocre) games labeled as "virtual-reality-interactive-movie (...)" were published. If I recall correctly, the first 3D VR helmet was called VFX-1 and was sold bundled with Descent and some dedicated joystick. I never owned one, and I read just one review which was mostly enthusiastic, but pointed to some weak points, like the eyes getting tired after an hour or so of playing. Then the whole thing basically flickered down and died.

I suppose the main reason it wasn't successful was that the hardware of the day was not powerful enough, the VR gear's design wasn't perfected to make it comfortable and natural to use, and the companies that made it failed to market it successfully. What I can't understand is why isn't there any development in the field today. There is some vr-ish hardware mostly targeted at the consoles (Kinect, Wii remote, TrackIR), but all projects of creating some 3d head-mounted display system seem to be in early infancy, appear once in a trade show somewhere and aren't heard of again.

I think it could work great with head tracking and some of today's shooters, flight sims (trackIR is nice but the movement scale translation is awkward) and other games with an FPP POV. Is there any technological reason why decent vr headgear can't be made today, or is it just that nobody really cares/everyone is scared to repeat the '90s failure?

# Answer
> 10 votes
There are multiple levels of what you are calling VR.

**Translated Head Tracking**

On the PC companies like TrackIR release devices precisely for doing this sort of thing. And several games, mostly on the flight simulation side, have support the head tracking.

ARMA II + TrackIR Demonstration

There hasn't been anything like this available in the console space but that may be changing soon. For example it's possible to do something very similar to what you see with TrackIR using the Xbox Kinect. Imagine the player playing with a standard controller and the Kinect tracks the movement of the players head and translates it on screen. There are two problems with this though:

1. The amount of processing power needed to find the players head and track movements. Not to mention that any mistakes in tracking can be hugely distracting.
2. This limits the locations a player can sit while playing a game. On the PC you tend to sit directly in front of and in the center of the monitor. On the console side people sit at all sorts of distances and positions from their TV. And effect like this works best only when you are centered to the display device.

**Head Mounted Displays**

This is the VR helmet style step the people often think of when VR is mentioned. There are several problems with HMDs.

1. Displays were often heavy, leading to neck fatigue. This will improve over time as display tech gets smaller and lighter.
2. Displays were low resolution. This has basically been addressed as an offshoot of the advancements in the mobile phone market. There are now lots of relatively cheap high res small screen technologies.
3. Safety issues with enveloping displays. To really feel immersed you want to block out the players vision outside the screens in the HMD. Of course in doing so players my trip and fall over something in the real world. No one wants to take that lawsuit risk.
4. Displays need a connection to content source. If you want console level graphics/games in your HMD, then you need to connect your HMD to a console. So now you've got a cable running to your head which hurts in a world of wireless controllers and communication. There are some advancements in wireless video transfer, but then we start to run into battery issues with the display itself, if it doesn't have a constant source of wired power.
5. Control issues related to 360 movement. If your game requires you to turn around to look behind you this doesn't mesh well with peoples living room furniture. People play games sitting on a couch or chair and they often are restricted in where they can move. This effectively limits the control input of an HMD to the level of the translated head tracking above, which can be done with much simpler technology.
6. HMDs are inherently isolating. Recent market expansion in games has come from more social experiences: dancing, music, and motion games. Building an expensive piece of technology for a smaller market isn't economically viable.

# Answer
> 2 votes
Technology just is not as advanced as we think it is.

You said the answer your self, "the hardware of the day was not powerful enough" and it's still not.

The kinect is a massive leap forwards technologically not just another piece of retail hardware.

To demonstrate my point nintendo released the wii motion plus for their controllers because they were not accurate enough for the newer game being developed.

# Answer
> 1 votes
My opinion: I think the fact that it's been tried and failed several times should hint that the fundamental problems haven't yet been overcome. Users aren't interested enough in the 3D / immersion, and the downsides (the requirement to wear head-gear) are more than enough to outweigh the interest.

Certainly everyone I've ever spoken to about it says something along the lines of 'maybe, if the glasses were cheap, and looked just like glasses'. And it's hard to make display glasses which are equivalent in terms of lightness and comfort to regular glasses; even before you get into the display quality or issues of mixing the virtual display with the ability to see the real world.

Maybe, if there was a tech advance that meant the displays could improve on previous efforts in terms of functionality, but cheap enough to come somewhere near the mass market. Until that tech advance comes, this will stay an expensive prototype that you only see at tech shows.

In a similar way, I think that even the requirement to wear inert glasses is enough to put many people off the new wave of 3D TVs. If 3D is really to become the new standard, there needs to be an evolution in display technology that lets the display show 3D, without the need for observers to be wearing / doing anything.

# Answer
> 1 votes
I'm sure there are several factors.

Head-tracking technology is usually pretty bulky and expensive to produce. That means it's also expensive for consumers to acquire and since there are so few games that utilize it, it's kind of a catch-22. Similarly the lack of penetration or interest in the technology means that not much money has been devoted to researching miniaturization of the relevant technology for the consumer space, so the devices aren't getting smaller or cheaper.

Furthermore, the requirement to wear such a thing drastically reduces the social aspect of the game-playing experience, which is a major trend in popular gaming right now -- especially when paired with the direction that controller technology has taken (focusing on much less encumbering devices that allow much more freedom)... such as the Wii and the Kinect.

A headset is bulky, complicated, and isolating, which means it's much more of a hardcore gamer's type of thing. The hardcore market is a lot smaller *and* a lot more discerning, usually, so with that in mind I can see how this catch-22 came about. It takes a lot of money, a lot of smart people, and a lot of marketing to make an alternative input device a common enough item, which is why it's ended up being basically a thing that only first-party console designers can seem to pull off -- and even then, they've had a poor track record (consider Nintendo's prior attempts at doing so -- not all of them were particularly successful).

# Answer
> 0 votes
In a certain sense VR technologies are becoming very mainstream actually, as now every smartphone has motion sensors built-in. Similarly the Wii controller has very advanced motion sensors, and Kinect takes that even further.

However if by "VR gear" you are particularly talking about Head-Mounted Displays, then the reason those have fallen out of favor is simple: people don't want to have big clunky displays strapped onto their heads.

# Answer
> 0 votes
This is an older question which highlights how fast things have developed in the past few years.

The real challenge with VR is the tracking latency. The headset must track head movements in real-time or the overall effect is physically nauseating.

The expense of VR headsets has been reduced to virtually (pun) nothing with Google's Cardboard VR. You only need to acquire the plastic lenses. If you have recent android smartphone, you already have all the rest of the hardware (projection and tracking).

Google provides a low-latency tracking API which is constantly being improved. There are two ambitious commercial applications currently of note:

http://www.volvocars.com/us/about/our-stories/google-cardboard

http://www.jauntvr.com/content/

While the technical problems of latency and price have been overcome, VR is still waiting for the killer-apps to generate a viable marketplace.

---
Tags: 3d
---


# Question
Title: How can I resize my Blender models when importing to Unity?
I made a 3D model in Blender, but when put it in my Unity project and add an FPS-camera the camera is bigger then my model. I used the measurements of Blender (that one cube is 1 meter in Unity).

How can I fix this?

# Answer
> 4 votes
Take care about unity import settings...

If you click on your model in unity you will see scale factor among the parameters. Take care the value is correct to fit your needs.

---
Tags: unity, models, scale, importing
---


# Question
Title: How can I make animations "snap" between transitions in Unity?
I have an animator with a few animations in it. These are very basic animations, just changing a transform to slide a sprite around in a cutscene. The issue that I'm running into is that when I transition from one animation to the next it will try to smooth out the animation differences. So if I have something move off the right of the screen, then with the next animation come falling from the top of the screen, it will first quickly slide to the new position.

I've tried to change the last frame of the first animation to Right Tangent -\> Constant, and the first frame of the second animation to Left Tangent -\> Constant. It didn't make any noticeable difference.

I also set up two functions (one for X, one for Y) to set the position at the beginning of the second animation, but only one of them were called, and it didn't seem to do anything.

So, how do I get an animation to snap to the starting values of the new animation after a transition?

# Answer
> 3 votes
I finally figured it out.

After selecting the animation transition you can see in the inspector a section with some bars. This shows how long the transition between the two animations will take. You can slide the bar over so that it shows 50%, telling you that the transition will be instant.

Or is it? Select the dropdown next to the padlock at the top right and select debug. The field that we want to change is Transition Duration. Set it to 0 to make it instantaneous.

# Answer
> 1 votes
You might just try hiding whatever it is until the frame where it's in position. Otherwise, it sounds like you want a Broken animation curve.

See also: Unity Manual: Editing Curves

---
Tags: unity, animation
---


# Question
Title: How can I separate component functionality from networking logic?
Is it possible to make network independent components that allow networking details to be specified externally?

For example, if I have a "Follow" script that follows a game object, it would need to do certain actions on the server and certain actions on the client. However, these things can change based on the network architecture. Single player games would not even need to consider what runs where. That makes perfect sense, except why should a component as general as "Follow" need to be different across different types of game?

I've tried creating a base component class that figures out how to call each method based on options set in the editor, but that failed due to RPC names needing to be different across all components attached to one game object. Not to mention it was messy. I've tried abstracting method calls to figure out how they should be called, but that doesn't solve the problem of WHICH methods should be network invoked.

I really don't want to build this into the components themselves, even though it might be the easiest / most obvious solution. That would destroy their portability across projects.

# Answer
It sounds like your intuition is correct and the components should be separate. However, I would look for better abstractions. For example, you say:

"a base component class that figures out how to call each method"

Putting Unity aside, this is something of a design anti-pattern (in OOP). You'll wind up with messy classes that don't have a clear purpose and do too broad a variety of things (violate Single Responsibility). You will also have a base class that has knowledge of the more specific derived classes (the inverse of what you want). Instead, try to break the functionality into *logical* parts and use those as class boundaries. Here's an arbitrary example of classes you might create:

* FollowBehavior - keeps one object at a given proximity to another object
* FollowNavigator - determines which coordinates an object should move to when *following* (consumed by FollowBehavior)
* NavigationClient - Sends requests to a server to move an object from one set of coordinates to another (optional)
* NavigationPredictor - used to smooth the rendering on the client by anticipating acknowledgements from the server. Helps avoid server lag.

You can see that each class is responsible for a very specific task. They are also modular. e.g. You might keep the general follow behavior, but "plug in" a new FollowNavigator for a new experience. Hope that helps.
> 7 votes

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


# Question
Title: Responsibility of rendering in a component/entity game engine
I am developing a simple component/entity game engine in C# (https://github.com/alexvm/BlueShift) and have a few questions regarding the responsibility of certain items in the engine itself. I have the following:

* Scene
* Entity
* Component

I am planning to have the scene maintain a collection of entities. To draw components on screen, the scene will loop over entities draw any components that extend from a drawable parent.

E.g. a drawable component might look like:

```
public class SpriteComponent : Drawable {

}

```

And in as scene I would call:

```
foreach(var entity in entities) {
    Scene.DrawComponents(entity.DrawableComponents());
}

```

Does the responsibility of each class make sense? I.e. does it seem like good design for the scene to maintain all entities and for the entity to present the drawable components to the scene to draw?

# Answer
> 2 votes
This kind of defeats one of the main purposes of having components in the first place. What I think you actually want is something like this:

```
class SpriteSystem
{
    void SpriteSystem::Draw()
    {
        foreach(var sprite in sprites)
        {
           this.DrawSprite(sprite);
        }
    }
}

class Sprite
{
   public Sprite::Sprite()
   {
       SpriteSystem::Register(this);
   }

   public Sprite::Destroy()
   {
       SpriteSystem::Unregister(this);
   }
 }

```

Every time a sprite is created, it should register itself with the sprite system. It should unregister when it is destroyed. The sprite system draws all registered sprites. This has several significant advantages:

* No need to find all the drawable components
* Can take advantage of batching
* Much better cache locality
* No need for vtable lookups with virtual functions
* No need to reference every possible type of thing in a generic "rendering system" as in the visitor pattern

Each and every type of component should have it's own system for drawing and updating itself. You should not have to reference entities or traverse a reference graph of entities to draw or update *anything*. The only purpose of entities is to loosely associate components into a container. That's one of the main points of having a component system.

# Answer
> 1 votes
I'm currently using the Visitor Pattern (Wikipedia link) as the basis of my rendering system for my game.

Basically, I have several interfaces defined to support this: (Note, this is basically an abstract recreation of part of my games system, and most likely does not reflect current code)

```
interface ISystem
{
    void Accept(EntityBase entity);
    void Accept(EntityActor entity);
    void Accept(EntityItem entity);
    // and so on
    void Draw(ComponentVisual visual, TransformComponent transform);
}

interface IAcceptee
{
    void Apply(ISystem system);
}

```

And then the classes

```
class RenderSystem : ISystem
{
    public void Accept(EntityBase entity)
    {
        // set effect here
        Draw(entity.GetComponent<VisualComponent>(), entity.GetComponent<TransformComponent>());
    }
    public void Accept(EntityActor entity)
    {
        // set effect here
        Draw(entity.GetComponent<VisualComponent>(), entity.GetComponent<TransformComponent>());
    }
    public void Accept(EntityItem entity)
    {
        // set effect here
        Draw(entity.GetComponent<VisualComponent>(), entity.GetComponent<TransformComponent>());
    }
    // etc
    public void Draw(ComponentVisual visual, TransformComponent transform)
    {
        // drawing code here
    }
}

// example of an entity
class EntityBase : IAcceptee
{
    public void Apply(ISystem system)
    {
        system.Accept(this);
    }

    // other entity data
}

```

And to use

```
ISystem render = new RenderSystem();

// ...

foreach (EntityBase entity in entities)
{
    if (entity.HasComponent<VisualComponent>())
        entity.Apply(render);
}

```

And yes, I do use Apply/Accept instead of Accept/Visit that the Wikipedia article uses in its examples. Personal preference.

The advantages of this is that the game has a collection of systems (may include different rendering systems), and I can swap between them (eg swapping between Dx9 and Dx10 3d rendering systems)

My components only contain data (position, visual, health, etc) and don't care about the entity they are attached to, my entities know they can apply a system which will use their components, and the systems only care about accepting entities.

You might want to move the `entity.HasComponent<Component>()` call into the system itself as part of an `CanAccept` function, which would be added to the `ISystem` interface, and implemented by each system. I would do the same, except I'm slightly hesitant about diving into a true ECS (Entity Component System) implementation, and I still have different entity classes with components explicitly declared (so instead of calling `entity.HasComponent<VisualComponent>()` I call `entity.HasVisual` instead.

I originally had Components for drawing, receiving input, updating, etc, but then I quickly ended up with duplicated components, components subclassing other components to extend it and add extra functionality, etc, and it was a mess. Moving to this pseudo Visitor Pattern based ECS has greatly simplified by own code, and made it much more understandable, not to mention the maintainability.

In the end, use what feels right for you. I was once stuck at the same place you are now, trying to decide how to implement a rendering system and what the best way was, and when I saw the Visitor Pattern, I knew that it is what I needed, and what I was going to use. You might feel the same when you spot some code or a design pattern that just seems to click and fit your requirements/needs.

# Answer
> 1 votes
Usually you will have your game **engine** alongside a rendering **engine**.

The System which contains the Render Components will not do the drawing. It will ensure each Render Component is properly synchronised with the current animation, position etc...

Concerning the rendering it will happen outside of your system in the render engine as you will have special optimisations that are not practical with a list of objects, or you might even have multiple rendering engines depending on the platforms you are working with.

Same thing applies to physics where your physics components will contain the physics objects from your physics engine and simply ensure all position and movement data is properly synchronised with the game engine.

---
Tags: c#, component-based, entity-component
---


# Question
Title: Setting up OpenGL on Mac OS 10.10 while keeping it cross-platform
I have experience with game programming mainly in allegro or drawing everything on native windows (No graphic libraries). Now I am interested in learning OpenGL for game development. I have found several OpenGL tutorials, but right now I only want to set up my environment so that I can be able to open windows and draw on them. I use Mac OS, but I am *very* interested in making all of my code as cross-platform as possible, so I would like to know how to set up (download, install, make a hello world kind of thing) OpenGL on a mac, but preferably without using Xcode or Apple depending stuff. I already checked to see whether my mac supports newer OpenGL and it does, so I will try to use the most recent standards.

I am ok with writing makefiles to link libraries and that kind of stuff that usually Xcode does for the sake of portability.

I keep wondering if I will need to always write some platform specific code when creating a mainly cross-platform game... and my guess is I will, but I want to minimize it. Anyway, I would like to know your advice for me. I hope my question is clear, but feel free to ask any detail you might need to know.

# Answer
I wrote this longish list of notes about cross platform stuff, but by the end I realized that @glampert's advice for GLFW is probably perfect.

I'll post this, anyway, maybe it is useful.

---

You can separate the concepts of “code portability” and “project portability”, though sometimes they go hand-in-hand.

Plenty of cross platform development efforts will use cross platform libraries, but just accept the hit of maintaining the separate projects & build systems, so that development & debugging can happen in the best local IDE.

You can certainly build Mac executables with gcc and make. The switches will differ slightly on Mac from Linux (for -framework and such), and needs 3rd party help like Cygwin to work on Windows.

The tool CMake will generate Visual Studio and XCode projects, as well as makefiles, from a single project description. (Although it’s kind of a quirky sometimes stubborn tool, it works.)

For code portability, you could use GLUT, or the more modern GLFW, or SDL2, or SFML to abstract out basic user input and window and OpenGL context management.

Another approach could be to use Eclipse IDE & Java, which presents a quite nice IDE which is the same on all platforms, and really “just works”. (A Java executable “jar” file needs a tiny launcher on each platform, but it’s trivial.) In Java you can use JOGL bindings to OpenGL. Opinions vary on whether performance differences between C++ and Java exist or matter…

And of course you could use a high level tool like Unity, which offers turnkey cross platform builds, but you're pretty distant from OpenGL at that point.

I think the shortest path to get up and going and have some fun with glDrawXxx is probably XCode project and GLUT (or GLFW?), and know that it won't be hard to write a Makefile to replace your Xcode project if you want.
> 1 votes

---
Tags: opengl, macos
---


# Question
Title: How can I move objects pixel by pixel in the scene editor?
I'm trying to find a way to move objects pixel-by-pixel(on my screen at least) in the scene editor. I tried a lot of different buttons but nothing seems to work, please tell me Unity has this functionality because doing it by mouse or by altering X and Y yourself is really tedious.

# Answer
> 1 votes
*I'm assuming you are working with 2D.*

There is no pixel-by-pixel concept in the scene view, its a 3D evironment, and all positions are represented by Vector3s which have floating point components.

Your camera view, on the other hand, can be set up in such a way that everything *appears* pixel perfect. This link is slightly out of date (it was published before the Unity 2D workflow) so you can safely ignore everything about setting up the sprites and spritesheets. The important parts are:

> ## Texture Filtering
>
> If you’re going for the “pixel art” look, then it’s absolutely critical that you set your sprite textures to use Point filtering mode, not the default Bilinear. Point filtering preserves hard edges in the source texture, keeping your sprites nice and clean:
>
> ## Orthographic Size
>
> The orthographic size expresses how many world units are contained in the top half of the camera projection. For example, if you set an orthographic size of 5, then the vertical extents of the viewport will contain exactly 10 units of world space. (The horizontal extents are dependent on the display aspect ratio.)
>
> To render the pixel-art look cleanly, you need to ensure that each pixel of the sprite’s source texture maps 1:1 to the viewport display. You don’t want source pixels being skipped or doubled-up, or your sprites will look distorted and “dirty”. The trick to ensuring this 1:1 ratio is to set an orthographic size that matches your vertical screen resolution divided by the pixel height of a sprite.
>
> Let’s say you’re running at 960x640, and you’re using 64x64 sprites. Dividing the vertical screen resolution (640) by the pixel height of a sprite (64) yields 10, the number of 64x64 sprites that can be vertically stacked in 640 pixels. Remember that the orthographic size is a half-height, so your target orthographic size in this case is going to be 5 (one-half of 10). It should look like this:
>
> If you set your orthographic size to half or double that target you may still get usable results, because the sprite’s vertical size will still divide evenly into the viewport’s vertical size. But if you set the orthographic size incorrectly, you will see some pixels skipped or doubled, and it will look very bad indeed:

# Answer
> 0 votes
It seems that you are looking for a debugger, that is if you aren't linking with visual studio, otherwise visual studio should work. Just make sure you set the breakpoints at the correct lines of code, probably in your update method.

If you want to see the per pixel update in your editor, just simply start debugging, then view the values with public fields in the editor.

http://unity3d.com/learn/tutorials/modules/beginner/scripting/monodevelops-debugger

---
Tags: unity, control, scene
---


# Question
Title: Efficient way to implement fog of war on a 2D grid with multiple actors
Lets say you have a 2D grid of tiles 100x100 and each tile can toggle fog on/off. To initialize the map you draw the tiles and toggle fog ON for each tile.

Now drop a single actor on the grid and use the actor's vision to determine which tiles need to toggle the fog OFF. As long at the actor stands still there is no further action required. When the actor moves you look ahead and toggle fog OFF on tiles near the destination and toggle the fog back ON for tiles in the area the actor is leaving. This implementation works well when there is a single actor but starts getting tricky when you add multiple actors.

Imagine the same scenario but now you have two actors standing on adjacent tiles. Initialization is the same, the initial vision is just based on each actor's starting point and vision distance. Now lets say one actor moves away while the second actor remains stationary. You can't use the original logic since, as the first actor leaves he will begin toggling the fog ON around the tiles where the second actor is standing (and still has vision).

I can think of two possible solutions and I'm wondering if there is something better that Im missing:

1. You could have the tile search the surrounding area for an actor with vision before toggling fog back ON but since an actor can have an arbitrary vision distance the tile won't know how far out to search unless the tile is aware of the maximum vision distance.
2. Each time an actor moves you could loop through every actor and redraw all vision but that seems inefficient if you have a large number of actors, especially if there is not a lot of simultaneous movement.

# Answer
Instead of binary fog on-off, you can have "tileSeenBy", starting with 0. Every time an actor sees a tile, they increment tileSeenBy by 1. Every time they move and don't have it in their field of view anymore, they decrement. If it's 0, nobody sees it. Super fast to calculate and check.

I know it's a bit costlier in terms of storage, but will save you calculations. For 256 max actors in the level sharing the fog of war, you need a ubyte per fog tile. For 65536, you need a ushort, and so on.
> 4 votes

---
Tags: fog-of-war
---


# Question
Title: How to put the game object to the upper left corner of the screen in Unity and make it visible entirely on all screens of mobile devices
I have game object which displays health indicator in my 2d video game in Unity. This gameobject contains a lot of sprites and i put it into left/top corner of the screen. In my game editor it is visible entirely but on my mobile device is visible only half of it. How can i make it visible entirely on all screens? Can anyone help me to solve this problem please.

P.S. I have some ideas how to do this: 1. Create health indicator from GUITexture elements. But it is not good for me, because health indicator consists of a lot of small elements and it will take a lot of time for me to resize every GUITexture according to my needs.

2. Put my gameobject with health indicator into another gameobject with zero transform, and then put parent GO into top/left screen using Camera.main.WorldToViewport method.

But may be there is more easy way to do this?

# Answer
From Unity 4.6 on the GUI system easily allows you to place any texture or sprite in screen space. It allows you to build complex HUDs including helath bar. See this video for an introduction
> 2 votes

---
Tags: unity, coordinates
---


# Question
Title: How is a Game Manager supposed to be constructed?
I'm a beginner developing games on Unity3D and now that I've become a little bit familiar with `GameManagers` I've been wondering about certain aspects.

How do you contruct a `GameManager` in the most efficient way? Since it's an entity that persists through scene loads, it has to be tweaked to reset some values on level load because it doesn't do that by itself.

I'm making a 2D platformer, so when a new level is loaded (or the current level is restarted) the `GameManager` has to dynamically find references to the objects it handles. And because each level cannot be identical to the next, should I have code in the `GameManager` to find references to the specific `GameObjects` and values depending on the level? I'm thinking something like this:

```
public class GameManager : MonoBehaviour {

  //Values and core methods etc

  void OnLevelWasLoaded(int level) {
    if (level == 1) {
      //Find references and set values for level 1
    }
    if (level == 2) {
      //Find references and set values for level 2
    }
  }
}

```

Or should I have a separate `GameManager` for values, game states and events and an in-between script for handling the `GameObject` references? I just want to learn this right. I'm worrying that if I dump "everything" in the `GameManager`, it becomes too big and inefficient.

Speaking of which, is it OK for the `GameManager` to also handle the UI/HUD? Or should there be a separate `UIManager` dedicated for this task?

# Answer
> 3 votes
UI and HUD is better managed elsewhere. the `GameManager` is supposed to manage the game state and transitions between game states and nothing else. Possible states could be `title`, `menu`, `loading` or `ingame`. Note that there are *not* states for every level like `levelXY`.

See the scene/level as the data for a state. You might come into a situation where need to specialise for certain levels like having state for `carchase` or `indoor`. You will have a persistent game object that holds the `GameManager` and other managers. Keep in mind that it must be a singleton or you will end up with multiple `GameManagers`.

Additional managers could handle music so you could have music playing during game state transitions.

---
Tags: unity, game-design
---


# Question
Title: Game upgrade launch : Cross-platform release timing
I just finished doing a major upgrade for a old mobile title, that haven't seen an update in over a year. Lots of new content, things are looking nice.

Sadly, these days it takes an average of 12 days to get the update through the iTunes approval tube, but less than 2 hours to throw it live right away on Google Play.

If i put the version up now, i can hit the autumn vacation period on android at least, and iOS people will have to wait till their version has been approved.

But I hear from other studios that they wait and launch both updates at the same time, to reach a socalled "synergy effect", since (as I understand it) attention to the update spills over to the mirrored platform.

But... I am simply skeptical on this. Is this effect really so strong, that you would postpone launches for weeks ? And googling for a bit, I'm having a hard time finding any numbers that can back this strategy up.

To put it more direct : **Is holding back a app launch till all platforms are in sync really "worth it" ?**

Ofcouse I will hold back my PR-horses till the upgrade is ready for both platforms, but is it really that bad to do a "premature" launch of an app on one platform ?

If anyone can back this strategy up with more than just a gut feeling (numbers and charts are always great) I am all ears. I'm not doing anything to my app untill I have some solid intel on these upgrade strategies.

PS: I am aware the same method is being used on initial app launch, where in a way it makes more sense to me. If you have any data on how strong the benefit of this strategy is there, I'm all ears too.

# Answer
Ok since you want numbers, I can only guarantee you one number: 1. That's me. But some things can't be put into numbers, and that's how people feel about certain things.

When you release updates for different platforms at different times, and assuming the user are already waiting for this update, the users who have to wait longer get the feeling of being on an second class platform. On the other hand, if you release "premature" updates only on one platform and not on the others, then this community might feel like a test environment, like rats. I personally don't like it to play unfinished/broken games unless I am aware of that and in the mood to do so. I think if you explain the the community that on iOS the validation process generally takes much longer then the desync of releases might have no noticeable affect on the community. Just be honest with the community, and don't lie to them.

A different story is it when your game has multiplayer. Then you should make sure that everybody has access to the same version at the same time. It's not nice when somebody can't play with his friends, because he does not have access to the same version.
> 1 votes

# Answer
Depends solely on the Game play !

During the project postmortem of failed games the development manager has to justify the failure and at such times the **launch date** is one the best escape excuses. But the truth is it was the bad content selection from day one itself.

If the game content and game play is really fabulous then after the Quality assurance is complete I do not see any reasons for holding the release.

You wait for the cross platform coherency just to make sure maximum number of downloads. Because once the bad reviews/ratings have been posted then hardly anyone would like to try the game.
> 0 votes

---
Tags: mobile, marketing, appstore, google-play
---


# Question
Title: Why I don't have the DX templates even with the Windows 8 SDK installed?
I have Windows 7, 64 bit.

I installed the Windows 8.1 SDK from here, and I installed Visual Studio Ultimate 2013. I chose to install everything; the size of the install was around 11GB.

Yet I don't have any of the templates shown here. What am I doing wrong? Do I need to install some other version of Visual Studio, like Express? Do I need Windows 8.1?

# Answer
> 2 votes
The official Visual Studio "DirectX" templates are only for Windows Store apps for Windows 8.x and Windows phone 8.x. They do not support Win32 desktop apps.

In order to develop Windows Store apps for Windows 8.1 or Windows phone 8.1 apps, you need:

* VS 2013 (any edition except Express for Web and Express for Windows Desktop)
* A Windows 8.1 system

In order to develop Windows Store apps for Windows 8.0 or Windows phone 8.0 apps, you need:

* VS 2012 or VS 2013 (any edition except Express for Web and Express for Windows Desktop)
* A Windows 8.0 or Windows 8.1 system

VS 2013 only supports Win32 desktop development when hosted on a Windows 7 system. You can certainly develop a DirectX app on such a system as a Win32 desktop app, but there's no built-in magic template to get you started. You create a standard Win32 desktop app, then add support for Direct3D from there. See Direct3D Win32 tutorial.

PS: The Windows 8.1 SDK is included as part of VS 2013 Express for Windows Desktop, VS 2013 Pro+, VS 2013 Community. You can download it as a standalone as you did as well.

---
Tags: directx, visual-studio
---


title: Three.js camera turning leftside right

text:
# Question
Title: Three.js camera turning leftside right
In Three.js I am trying to implement an orbiting camera can be rotated around the x and the y axis. I am using these two functions:

```
    function rotateX(rot) {
        var x = camera.position.x,
            y = camera.position.y,
            z = camera.position.z;

        camera.position.x = x * Math.cos(rot) + z * Math.sin(rot);
        camera.position.z = z * Math.cos(rot) - x * Math.sin(rot);

        camera.lookAt(scene.position);
    }

    function rotateY(rot) {
        var x = camera.position.x,
            y = camera.position.y,
            z = camera.position.z;

        camera.position.z = z * Math.cos(rot) + y * Math.sin(rot);
        camera.position.y = y * Math.cos(rot) - z * Math.sin(rot);

        camera.lookAt(scene.position);
    }

```

Now the x rotation works fine but the y rotation does not. Once I go over the top of the model as in that the camera's z position becomes negative then suddenly the lookAt method rotates the camera by PI amount on the Z axis and suddenly the left side of the model is on the right and vice versa. Now I can fix this by checking for a negative Z and then just fixing the camera's rotation but this then causes a malfunction when using x ad y rotation at the same time, the x then suddenly gets this inverting behavior.

How should I go about fixing this?

# Answer
> 2 votes
Your code is a little strange. If you want to rotate around the Y axis, then you change the X and Z coords, but you're altering Y and Z.

This code rotates smoothly around Y:

```
function rotateCameraY(radiansIncrement) {
var x = _camera.position.x; var y = _camera.position.y; var z = _camera.position.z;
var signx = x > 0 ? 1 : -1;

// get current radians from z and x coords.
var radians = x == 0 ? Math.PI/2 : Math.atan(z/x);
if (signx == -1) radians += Math.PI;

radians += radiansIncrement;
if (radians > Math.PI*2) radians = radians%(Math.PI*2);
while (radians < 0) radians += Math.PI*2;

var radius = Math.sqrt(x*x + z*z);
_camera.position.x = radius * Math.cos(radians);
_camera.position.z = radius * Math.sin(radians);
}

```

You can see it at work here: http://formulatoy.net

---
Tags: javascript, camera, rotation, three.js
---


# Question
Title: How do I implement melee hit boxes for a top-down game?
For a 3D top-down game, how should I handle collision in melee combat? My game has no targeting system, so I can't use a simple distance check between attacker and target.

What I am thinking is have the character swing, generate a hit box, run the damage script for any characters in that hit box, and then delete the hit box. How should I handle this?

Also, I would like to use the same attack script for all players and NPCs in melee, even with different attack animations and hit boxes. However, really I can't figure out how to reliably assign who the attacker and who the target are within that script, or how to handle multiple simultaneous attacks.

# Answer
> 1 votes
I think you and the commenters are on the right track. Ideally the hitboxes wouldn't have to be recreated on each attack (unless the nature of the attack were to change, maybe?). You could add something like this to every `GameObject` that can attack, along with a hitbox `Collider` marked as a Trigger.

```
public class HitController : MonoBehavior {

private Queue hitQueue;
private int health;
private int damage;
private bool attacking;

public void Start() {
    hitQueue = new Queue();
    health = 10;
    damage = 3;
    attacking = false;
}

public void Update() {
    // rudimentary attack input..
    if (Input.GetKeyDown(KeyCode.Space)) {
        // play an animation, etc...
        attacking = true;
    } else {
        attacking = false;
    }
    //  ...
    HandleHits();
    //  ...
}

private void HandleHits() {
    if (hitQueue.Count > 0) {
        Hashtable hitData = hitQueue.Dequeue();
        string name = hitData["name"];
        // do something with the attacker's name if you like
        int dmg = hitData["damage"];
        // could do further processing with attacker's damage..
        health -= dmg;
        if (health <= 0) {
            //however you wanna handle this
        }
    }
}

public void SignalHit(Hashtable hitData) {
    hitQueue.Enqueue(hitData);
}

public void OnTriggerEnter(Collider c) {
    // we only care about collisions if we're attacking
    if (attacking) {
        HitController hc = c.gameObject.GetComponent<HitController>();
        // this will hit other HitControllers, but not handle other collisions
        if (hc != null) {
            Hashtable h = new Hashtable();
            h.Add("name", this.name);
            h.Add("damage", this.damage);
            hc.SignalHit(h);
        }
    }
}
}

```

---
Tags: c#, unity, collision-detection, 3d, combat
---


# Question
Title: How to detect when a moving rectangle (sprite) is tapped
I am new to Monogame. I am currently developing a simple game, just to learn some basics of Monogame development. The idea here is to detect whether or not the user has tapped on a a rectangle (represented by moving sprite) and `return true` if they did or `false` if they did not, but it always returns false, even if I tap on the sprite. The pertaining functions are here:

```
// Part of Update function
protected override void Update(GameTime gameTime)
{
    touches = TouchPanel.GetState();

    if (CheckRectangleTouch(arlington.BoundingBox, touches))
    {
        arlington.spritePosition = new Vector2(200, 200);
    }
    else
    {
        arlington.spritePosition = new Vector2(100, 100);
    }
}

// Collision function
private bool CheckRectangleTouch(Rectangle target, TouchCollection touchCollection)
{
    if (touchCollection.Count > 0)
    {
        if (target.Contains(touchCollection[0].Position))
        {
            return true;
        }
    }
    return false;
}

```

Any idea why is this code not working, or about a better method for collision detection?

# Answer
> 0 votes
The most likely reason that your sprite is not reacting to your touch is that you are touching at multiple places on the screen, according to Monogame, which probably don't all collide with the sprite. When you check for touch, you only check the first detected touch position, which here does not seem to come in contact with your sprite based on your results. The touch you are detecting is most likely on the sides of the phone where you are holding it or something similar. The solution to this is to check all of the touches within the `TouchCollection` instead of just the first one in the array.

```
private bool CheckRectangleTouch(Rectangle target, TouchCollection touchCollection)
    {
        if (touchCollection.Count > 0)
        {
            foreach (var touch in touchCollection)
            {
                if (target.Contains(touch.Position))
                {
                    return true;
                }
            }
        }
        return false;
    }

```

Note that in this version of the function, I am looping through the collection with a foreach loop and checking if *any* of the touches collide with the sprite, instead of just the first element.

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


title: Unity: Built In Scrollable Containers?

text:
# Question
Title: Unity: Built In Scrollable Containers?
Is there a way to get a scrollable container in Unity without purchasing a plugin such as NGUI or TK2D?

I want to create a scrollable container of interactive elements that can be clicked on individually and be scrolled horizontally by the user dragging their finger. You can kind of think of this as something similar to the shop menus in Clash of Clans. Here's a quick mock that I made to demonstrate the behavior I'm looking for: https://www.youtube.com/watch?v=bOJSMDPdFUQ

Is there a built in way to do this in Unity without the need of purchasing an extra plugin such as NGUI or TK2D?

# Answer
> 0 votes
Yes.

Unity has this functionality built in. Both the legacy GUI system and the new GUI system have scollable containers. Depending on how you show the containers, they can both achieve the functionality you're after.

---
Tags: unity, ngui, gui
---


# Question
Title: Unity3D -- WAV plays an octave too low on Android
I have generated a synthetic 'concert pitch A' tone from sinewaves.

It plays properly on OS X player, and on my Android device.

Now I record myself singing a 'concert pitch A' into the microphone as a MONO .WAV -- foo.wav.

In Unity I add foo.wav to my resources, making sure to turn off "is 3D sound" in the settings panel.

I then create a script that loads it into an audioclip and extracts the contents into a float buffer:

```
    AudioSettings.outputSampleRate = 44100; // just to be safe

    AudioClip phonemeClip = Resources.Load( filename ) as AudioClip;

    float [] phonemeBuf = new float[ phonemeClip.samples * phonemeClip.channels ];

    phonemeClip.GetData( phonemeBuf, 0 );

```

I then add this sound to my synthetic tone, 30000 samples in (so nearly 1 second):

```
    float PHONEME_VOL = 0.3f;
    int OFFSET = 30000;

    for(int i=0; i<phonemeBuf.Length; i++)
        if( OFFSET+i < buf.Length )
            buf[OFFSET+i] += phonemeBuf[i] * PHONEME_VOL;

```

On OSX player this works perfectly.

However on my android device the original synthetic tone plays correctly whereas the added foo.wav appears to be exactly an octave low.

What might be causing this?

I suspect it may be converting the clip into a stereo clip, with 0 for the right channel. That would interpolate the resultant float buffer with zeros, which would certainly take it down octave.

But I can't see how to address this problem.

# Answer
> 1 votes
The output rate on Android could be locked to 22Khz or depend on the devices. In this case you will have to adjust the mixing rate in software:

```
//        foo.wav speed * 8bits of fractions / outputSampleRate
int speed = 44100 * 256 / AudioSettings.outputSampleRate;
for(int i=0,j=0,max=phonemeBuf.Length * 256; j<max; ++i, j+=speed)
    if( OFFSET+i < buf.Length )
        buf[OFFSET+i] += phonemeBuf[j >> 8] * PHONEME_VOL;

```

Or it could have been converted to stereo. try:

```
int c = phonemeClip.channels;
for(int i=0, j=0, max=phonemeBuf.Length; j<max; ++i, j+=c)
    if( OFFSET+i < buf.Length )
        buf[OFFSET+i] += phonemeBuf[j] * PHONEME_VOL;

```

ideally, combine both sample-rate conversion and mixing only the left channel.

```
int c = phonemeClip.channels;
int speed = 44100 * 256 / AudioSettings.outputSampleRate;
for(int i=0,j=0,max=phonemeBuf.Length * 256; j<max; ++i, j+=speed)
    if( OFFSET+i < buf.Length )
        buf[OFFSET+i] += phonemeBuf[(j >> 8)*c] * PHONEME_VOL;

```

---
Tags: unity, audio
---