title: Game over pop-up like Flappy Bird

text:
# Question
Title: Game over pop-up like Flappy Bird
How can I make a game over pop-up like Flappy Bird in cocos2d-iphone 3?

I tried to add a new Scene, but it adds a new screen on the game, I just want a rectangle with some buttons inside it. I also search how to add multiple scene, but didn't find an example doing it.

# Answer
> 3 votes
Add a new Layer and put there a Menu object with the buttons you need. Make the layer visible when the game is over.

# Answer
> 0 votes
I don't have experience with the engine you're talking about, but can't you just add the 'game over' image as an object with transparent backgrounds, the places where they need to be transparent?

---
Tags: cocos2d-iphone
---


# Question
Title: HLSL float4 addition returning all 0.0f vector, unexpected result
Edit: Added images at the bottom to show the current issue.

I have the following few lines in my hlsl pixel shader where color and specular are both float4.

```
color = color * textureColor;

// Add specular component and clamp
color = saturate(color + specular);

```

Running VS2013 graphics debugger and debugging into the pixel shader I see specular coming through as (0.0f, 0.0f, 0.0f, 0.0f) which I expect for the pixel I'm checking since it's not within the specular portion of the viewDirection, but the float4 addition is making the final color as zero after the addition.

Am I completely missing something here? I would assume the following math:

```
   color (0.65f, 0.0f, 0.0f, 1.0f)
 + specular (0.0f, 0.0f, 0.0f, 0.0f)

   result = (0.65f, 0.0f, 0.0f, 1.0f)

```

Any thoughts would be greatly appreciated. I have a feeling, I'm missing something really simple here.

EDIT:

```
 // If I remove the specular and return color after multi by tex Sample,
 // I get the following expected result
 color = color * textureColor;

```

```
// As soon as I add the specular component back in
color = saturate(color + specular);

```

# Answer
Finally got some good time to go back and study this in more depth. In the end it was two simple issues. First my shader constant buffer variable order didnt match the struct I was using to map. Once this was corrected the black portion was corrected but there was still the large solid white spot being calculated versus the small expected specular glow. This was corrected by dividing the view direction vector by its length for normalization.
> 2 votes

---
Tags: directx, hlsl
---


title: Unity - Light and sprite collision

text:
# Question
Title: Unity - Light and sprite collision
I'm a beginner in Unity and i'm facing a little problem / question. The main purpose of my 2D game is based on the mouvment of a specific light and the player have to avoid getting inside his rays. My actual game got different type of layers :

1. Z = -5 : A front light (don't pay attention of this one)
2. Z = 0 : The main scene, where the player move and interact with collider (2D based, player is a sprite with rigidbody2d and circlecollider2d
3. Z = 1 : Some elements to avoid the light to go through and give the player a chance to hide
4. Z = 10 : The main light that the player have to avoid

My problem is the following one, i don't know how to interact a Point Light (so a 3d object) and a sprite (2D). I tried to do some "OnTriggerEnter / Stay" in the Point Light but it never trigger. I heard about "Raycast" but i prefer to ask some solution before learning this. If anyone can give me tips, it would be very good :)

Thanks !

\[EDIT SOLUTION, THANKS TO Géry Arduino\]

```
#pragma strict

public var moon : Component;

function Start () {

}

function Update () {
var radiusMoon = moon.transform.light.range;
var zMoon = moon.transform.position.z;
var zPlayer = transform.position.z;
if(zMoon - radiusMoon <= zPlayer) {
    var zDirection = transform.position.z - zMoon;
    var xDirection = transform.position.x - moon.transform.position.x;
    var yDirection = transform.position.y - moon.transform.position.y;
    var direction = Vector3(xDirection, yDirection, zDirection);
    Debug.DrawRay(moon.transform.position, direction, Color.red, 10);
    if(Physics.Raycast(moon.transform.position, direction, radiusMoon)) {
        Debug.Log("there is something between me and the object....");
    }
    else {
        Debug.Log("i'm free");
    }
}
}

```

# Answer
> 2 votes
Actually Lights does not contain colliders, but what you can do is add a CircleCollider2D component to a light, then track if your object collide with the collider of this light and only then trace a ray from your object (character) to the light, if the ray hits a collider before hitting the light then you know your character is in the shadow part of this light!

I am not sure you could go away with this without using raycast2D, but dont be afraid once you get a hold on it it can be very straight-forward.

For example to put on your character :

```
private bool inTheShadow = false;

void Update() {
    if(!inTheShadow) {
        //Replace following lines with your own magic
        Debug.Log("Too much Light!!");
    }
    else { Debug.Log("Vampire Secure Area!!"); }
}

void OnCollisionStay2D(Collision2D coll) {

    if (coll.gameObject.tag == "Light") {//is that component a light? (need to have the light tag on your light
        float distance = Vector3.distance(transform.position,coll.gameObject.transform.position);
        Vector3 rayDirection = (coll.gameObject.transform.position-transform.position).normalized;
        RaycastHit2D hit = Physics2D.Raycast(transform.position,rayDirection,distance);
        if(hit.collider!=coll) { //Am i hitting the light or smthing else?
            inTheShadow = true;
        }
        else {inTheShadow = false;}
    }
}

```

This is a non optimized version done quickly without unity or anything related near hand

---
Tags: 2d, unity, lighting
---


# Question
Title: UV Texture coordinates out of [0,1] (WebGL)
I'm creating a 3D game with *WebGL* and i'm using Wavefront Objects as a base model format. I recently found some models, their texture coordinates of which are out of the typical **\[0,1\]** range and i really don't know how to handle them (in code).

I know of course this is a known issue, texture coordinates can be outside of **\[0,1\]** and the solution is to use **GL\_REPEAT** wrap mode.

But this is no solution to me since i have a lot of non-powered-by-2 textures and i need to use **CLAMP\_TO\_EDGE** wrap mode (the solution to non-pow-2 textures).

I tried to bypass this issue by coding, so to convert **\[0-,1+\]** ranges into **\[0,1\]** but with not much of success (although somewhat). Here's what i did: I looped **"vt"** entries (from my parser) and the cases i'm checking are these (pseudo):

```
U,V = texture coordinates as they come from file

if (U<0) {
   U = U + Math.abs( Math.floor(U) );
}
if (U>1) {
   U = U - Math.floor(U);
}
if (V>=0) {
   V = Math.ceil(V) - V;
}
if (V<0) {
   V = Math.abs( Math.floor(V) - V );
}

```

The above fragment will take a U,V of *unknown range* and will convert it into **\[0,1\]**, taking also care the *WebGL texture coordination system* (*0,0* buttom-left for WebGL but *0,1* for Wavefront, the 3rd case above)

The numbers are calculated correctly but the result is not the expected and i'm afraid there is a misunderstanding by my side on how the **GL\_REPEAT** mode works.

So my question(s)

* Can this be solved by code, so i can use **CLAMP\_TO\_EDGE**?
* In case there's no way, is there any program than can take a model of **REPEAT**-ed coordinates and produce one in **\[0,1\]** range? I'm already using *Blender* but could not find a setting for this in exporter.

# Answer
I think you would be better off re-sizing your textures to the nearest power-of-two. You won't need to adjust the texture coordinates as they are relative to the size of the texture image (although you may need to set v = 1 - v to account for the different origins).

The problem with wrapping the texture coordinates yourself is that filtering will not work correctly at the "seams" where a value goes suddenly from 1 -\> 0.
> 1 votes

---
Tags: javascript, webgl
---


# Question
Title: 2D animation is not rendered as it supposed to
I'm working with Melonjs, i have configured everything to update the character movement and still get this "delayed" rendering of the character.

below is the constructor

```
  // call the constructor
  settings.image='kit.walk';
  settings.spritewidth=56;
  settings.spriteheight=80;

  this.parent(x, y, settings);
  this.alwaysUpdate=true;
  // set the default horizontal & vertical speed (accel vector)
  this.setVelocity(3, 15);
  this.setFriction(0.4,0);
  // set the display to follow our position on both axis
  me.game.viewport.follow(this, me.game.viewport.AXIS.HORIZONTAL);
  this.renderable.addAnimation('walk',[0,1,2])
  this.renderable.setCurrentAnimation('walk');
  this.anchorPoint.set(0.5,1.0);

```

i'm not very familiar with the engine, but it doesn't seem to be a problem with the engine, i think is a configuration problem somewhere.. i tried to look into examples but nothing helped so far.

could it be a problem with the sprite?

# Answer
Apparently not declaring `backgroundcolor` as map property in Tiled and just leaving transparent background causes this.

Adding `backgroundcolor` with value `#191919` or any other color at `Map->Map Properties` will render correctly the animation.
> 1 votes

---
Tags: 2d, javascript, animation
---


# Question
Title: How to realize a camera that is following the player
I want to create a simple space game, like Asteroids. Unlike Asteroids, the map is supposed to be larger than what the player can see:

The grey part is what the player can see in the game window, to see the rest of the level he needs to move his spaceship. When his spaceship reaches the borders eventually, the camera is supposed to stop and not move any further. Thus, the spaceship wouldn't be central anymore.

I am using libgdx and have no idea how to do this.

# Answer
Well, it's rather like how you'd perform simple collision detections. You could consider the viewport and the edges of the world "axis aligned bounding boxes" (AABB). So, you'd just need to do checks like this: "Has the right edge of the viewport moved past the right edge of the world? If so, then change the viewport's postion on the X-axis so that the two edges are just against each other."
> 0 votes

---
Tags: camera
---


# Question
Title: Reconstructing mesh from topological skeleton?
I have a topological skeleton of a 3d maze-like level (think Descent\[I\]/II). It looks like a tree where each node is a vertex in 3d-space.

If it were on a 2d plain, I would "simply" use this to offset it and reconstruct the polygon. However, it's not a 2d skeleton and I am interested in 3d mesh outward offsetting it in 3d space.

What I tried so far is offsetting outward as if it were in 2d space and then extruding the flat shape into a 3d-object. This however does not work where two edges in the skeleton are close to one another as they intersect after this process.

Is there an algorithm or tool that accomplishes this?

I am trying to do the opposite of this I believe:

skeletonization

Please notice that this is a graph with simple cycles, in my specific case it's a tree.

Starting from a skeleton and getting a rough mesh **without buggy intersections**.

This is an example of what it would look like after being offset outwards (inflated). Minus the intersections of course.

# Answer
One approach would be to use voxels as an intermediate representation.

1. Render the skeleton line segments into a volume
2. Expand the volume belonging to the skeleton by iteratively filling voxels whose neighbours belong to the skeleton
3. Extract the resulting surface using the marching cubes (or marching tetrahedra) algorithm
> 1 votes

# Answer
Build shell mesh around every segment, feed them to some CSG processor, smooth resulting mesh.
> 1 votes

---
Tags: computational-geometry
---


# Question
Title: How do physics engines like Box2D detect and respond to collisions between arbitrary polygons?
I've always wondered how collision detection like this was achieved, and I've always wondered what the response would be. Do they perform line-line intersection tests for each line making up the two polygons? If it'd make the question any more specific, how does Box2D handle this?

# Answer
> 3 votes
2D collisions with non-rectangular shapes are often detected using the Separating Axis Theorem (tutorial here). Look it up, there are a lot of good articles on the subject.

Box2D uses it as part of the solution for their collision system, for a more in-depth view read their manual.

---
Tags: collision-detection, box2d, collision-resolution
---


# Question
Title: HLSL: using "?" operator in Technique section produces branches?
I recently found that you can do this:

```
int AnotherShaderConstant = 0;

float4 PixShader(VSOUT input, uniform bool Direction)
{
    float4 color;
    if (Direction)
        color = GoLeft();
    else
        color = GoRight();

    return color;
}

technique First
{
    PixelShader = compile ps_3_0 PixShader(AnotherShaderConstant == 1 ? true: false);
}

```

And it will work properly, meaning that you can change a shader constant "AnotherShaderConstant" at CPU level and the pixel shader will change it's behavior. The question is, will such move be equivalent to the following code that clearly produces a branch:

```
int AnotherShaderConstant = 0;

float4 PixShader(VSOUT input)
{
    float4 color;
    if (AnotherShaderConstant == 1)
        color = GoLeft();
    else
        color = GoRight();

    return color;
}

technique First
{
    PixelShader = compile ps_3_0 PixShader();
}

```

What I am trying to understand is will I recieve shader optimization similar to those that uniform constants provide, or will my code be bluntly submited to the GPU and executed for each pixel effectively resulting in a branch?

I mean the uber-optimized Microsoft's shaders from XNA's simple effects do the following:

```
int AnotherShaderConstant = 0;

float4 PixShader1(VSOUT input)
{
    float4 color;
    color = GoLeft();

    return color;
}

float4 PixShader2(VSOUT input)
{
    float4 color;
    color = GoRight();

    return color;
}

PixelShader PixelShaders[2] =
{
    compile ps_3_0 PixShader1();
    compile ps_3_0 PixShader2();
}

technique First
{
    PixelShader = PixelShaders[AnotherShaderConstant];
}

```

Which means that their shader compiler can react to changes in shader constants, will it react in such situation?

# Answer
I profiled a test app with NSight and the results clearly showed that using "?" operator in the techniques section produces branches.

When using this structure:

```
technique First
{
    PixelShader = compile ps_3_0 PixShader(true);
}

technique Second
{
    PixelShader = compile ps_3_0 PixShader(false);
}

```

the shader sent into GPU is optimized at the CPU level and produces NO branches. I had two branches in my shader: one with 4 instructions and the other with 129. The shader that was sent into the GPU (it's disassembly) had 4 instructions when I used First technique and 129 when I used Second.

This approach produced equal results:

```
PixelShader pixelShaders[2] =
{
    compile ps_3_0 PixShader(true),
    compile ps_3_0 PixShader(false),
};

technique First
{
    PixelShader = pixelShaders[AnotherShaderConstant];
}

```

However, this code:

```
technique First
{
    PixelShader = compile ps_3_0 PixShader(AnotherShaderConstant == 1 ? true: false);
}

```

Clearly produces a branch, as ANY shader sent into the GPU had 134 instructions regardless of what AnotherShaderConstant value was. The time it took GPU to process the Draw calls also varied:

For a model that used the simple (First) branch via specifying a different technique NAME or using the ARRAY of shaders took 13946 ms.

For the same model that used the simple (First) branch via changing the AnotherShaderConstant parameter and using the "?" operator took 58063 ms. So it was 4,16 times longer.

The number of rasterized primmitives and shaded pixels was the same in both cases.

**UPDATE:** Here is a quck and dirty sample of custom shader processor for XNA 4.0:

XNA 4.0 Custom Shader Processor

It compiles all the possible premutations of you shader depending on the number of directives you specify. At runtime, you can switch those shaders by simply changing needed variables.
> 3 votes

# Answer
Normally branches dependent on uniforms get handled by the driver. It is possible that a directX layer handles this even before the driver but it is not documented and pure speculation.

I have noted using AMD drivers that changing a uniform to the point of that one branch will start to be taken, the first time this happens I can get a severe lockup of the whole machine during 1 second. I suspect the driver to be re-compiling its shader-cache at this moment to be able to have the optimized version of the second branch. Which suggests that the driver compiles one distinct shader for each branch, caches it, and uses an indexing system (maybe a unique signature using uniform values hashing) and picks the optimized shader for that combination.

Microsoft also provides pre-shaders, which the fxc compiler will handle if not given the option to ban that stage. (because it can by buggy in complex shader codes) The pre-shader is a little stage where the compiler puts all the computation that will definitely be invariant for all pixels (the same result for one raster pass), and make the card (or CPU) execute that one time on one thread before the actual multi-threaded shader executes on the GPU, but stripped of the invariant code, and the result is passed by microsoft magic between the 2, surely using constant buffers.

with effects, you can use a trick which is to use 2 techniques with a `uniform bool` passed as a parameter of your lighting function. In which case the compiler will generate 2 different hard-compiled functions from the same code but without a branch.

real dynamic branches exists when the condition is dependent on something variant, like a fetching from a texture with a variable UV. (UV is taken from varying, or calculation). This case, the card has 2 hardware implementation depending on generation, older generations (shader 2/3) will execute both branches, one after the other, and the pixels(threads) will select the result from the branch that corresponds to them after all have been executed. Therefore the execution time is the sum of both branches. This is to be mitigated by the fact that thread blocks (often something like a 16\*16 pixel zone on screen) will run only one branch if all pixels of this block happen to have the same condition. Therefore you don't loose too much performance on very low frequencies conditions (like a shadow with one hard edge and all the left part of the screen is shadowed and all the right part is lit, in this case only the center blocks will suffer the slow down).

Second generation (shader 4/5) has actual CPU-like dynamic branching, in this case you don't care really.
> 2 votes

---
Tags: hlsl, optimization
---


title: In glsl, how do indices work?

text:
# Question
Title: In glsl, how do indices work?
I have made a vertex shader and fragment shader and kind of know how they work, and I know that you specify what index you want your vertices to be in inside the shader program. So if the vertex was at index 0, does each vertex take up 1 index? If each one took up an index, than how many indices would a matrix 4x4 take up? Sorry if thats confusing but I'm just starting and I don't really know how the indices within the shader works. So:

```
#version 140
in vec3 position; //This could be located at index 0
in mat4 randomMatrix; //If this came right after position, what index is it located at??
void main() {
    gl_Position = vec4(position.x * 0.5, position.y * 0.5, position.z * 1, 1);
}

```

Tell me if I have this all wrong.

# Answer
> 2 votes
The OpenGL wiki does a pretty good job of explaining it. I'd recommend specifying the inputs (for readability) with explicit locations:

```
#version 140
layout (location = 0) in vec3 position;
layout (location = 1) in mat4 randomMatrix;
void main() {
    gl_Position = vec4(position.x * 0.5, position.y * 0.5, position.z * 1, 1);
}

```

Each index essentially takes a vec4, so if you pass a `vec3` in `[x, y, z]`, it's going to get padded internally to `[x, y, z, 0]`. Same with passing a `float`, it would be padded to `[x, 0, 0, 0]`. A mat4, on the other hand, takes up `4 * vec4` of space, thus it'll take up 4 indices. In your example, if you added one more variable, after the matrix, it would look like this:

```
#version 140
layout (location = 0) in vec3 position;
layout (location = 1) in mat4 randomMatrix;
layout (location = 5) in float foo;
void main() {
    gl_Position = vec4(position.x * 0.5, position.y * 0.5, position.z * 1, 1);
}

```

The matrix uses attribute indices 1, 2, 3 and 4, one for each collumn.

---
Tags: opengl, c++, glsl
---


# Question
Title: JavaScript: Rotating a canvas around its center for a 2D sidescroller
I've been making a 2D sidescrolling game using JavaScript and HTML. The game is set in space, where the player character can fly around (Up, Down, Left and Right keys) and rotate the world around him (A and D keys). Here is the HTML and JavaScript code:

```
<body onkeydown="keyDown(event)" onkeyup="keyUp(event)">
<canvas id="graphics" width=600 height=400 style="position:absolute;margin:0 auto;vertical-align:middle;background-image:url('Black.png');"</canvas>

<script>
//VARIABLES
var gameCanvas = document.getElementById("graphics");
var grafx = gameCanvas.getContext("2d");
var player = new GameObject("Character1NoAAInvert.png", 268, 160, 64, 59);
var maxBlock = 5;
var block = new Array();
for (var i = 0; i <= maxBlock; i++) {
    block[i] = new GameObject('BlockInvert.png', i * 60 + 100, 300, 62, 62);
}

var img = new Image();
img.src = "Character1NoAAInvert.png";
var isA = false;
var isD = false;
var isUp = false;
var isDown = false;
var isLeft = false;
var isRight = false;
var rotation = 0;
var rotationVelocity = 0;
var canvasCenterX = gameCanvas.width / 2;
var canvasCenterY = gameCanvas.height / 2;
document.body.appendChild(img);
player.Gravity = 20;
player.Weight = 0.4;

//EVENTS
function keyDown(e) {
    if (String.fromCharCode(e.keyCode) === "A") isA = true;
    if (String.fromCharCode(e.keyCode) === "D") isD = true;
    if (String.fromCharCode(e.keyCode) === "&") isUp = true;
    if (String.fromCharCode(e.keyCode) === "(") isDown = true;
    if (String.fromCharCode(e.keyCode) === "%") isLeft = true;
    if (String.fromCharCode(e.keyCode) === "'") isRight = true;
}

function keyUp(e) {
    if (String.fromCharCode(e.keyCode) === "A") isA = false;
    if (String.fromCharCode(e.keyCode) === "D") isD = false;
    if (String.fromCharCode(e.keyCode) === "&") isUp = false;
    if (String.fromCharCode(e.keyCode) === "(") isDown = false;
    if (String.fromCharCode(e.keyCode) === "%") isLeft = false;
    if (String.fromCharCode(e.keyCode) === "'") isRight = false;
}

//MAINLOOP
MainLoop();

function MainLoop() {
    //PRE VARIABLE ADJUSTMENTS
    for (var i=0;i<=maxBlock;i++) block[i].X += -player.Velocity_X;
    for (var i=0;i<=maxBlock;i++) block[i].Y += -player.Velocity_Y;
    grafx.rotate(rotation * Math.PI / 7200);
    player.Velocity_X = player.Velocity_X * 0.98;
    player.Velocity_Y = player.Velocity_Y * 0.98;
    player.Rotation -= rotationVelocity;
    rotation += rotationVelocity;
    rotationVelocity = rotationVelocity * 0.5;

    //LOGIC

    if (isA) rotationVelocity += 0.1;
    if (isD) rotationVelocity += -0.1;
    if (!isUp && !isDown) player.Velocity = 0;
    if (isUp) player.Velocity_Y += -0.1;
    if (isDown) player.Velocity_Y += 0.1;
    if (isLeft) player.Velocity_X += -0.1;
    if (isRight) player.Velocity_X += 0.1;
    //if (player.Velocity_Y < player.Gravity) player.Velocity_Y += player.Weight;
    for (var i = 0; i <= maxBlock; i++) {
        if (player.isColliding(block[i]) && player.Y + player.Height < block[i].Y + player.Velocity_Y) {
            player.Y = block[i].Y - player.Height;
            player.Velocity_Y = 0;
        }
    }

//POST VARIABLE ADJUSTMENTS

//RENDERING

grafx.clearRect(0, 0, gameCanvas.width, gameCanvas.height);
grafx.drawImage(player.Sprite, player.X, player.Y);
for (var i = 0; i <= maxBlock; i++) {
    grafx.drawImage(block[i].Sprite, block[i].X, block[i].Y);
}
setTimeout(MainLoop, 1000 / 60);
}

function GameObject(img, x, y, width, height) {
    this.Sprite = new Image();
    this.Sprite.src = img;
    this.X = x;
    this.Y = y;
    this.Previous_X = this.X;
    this.Previous_Y = this.Y;
    this.Velocity_X = 0;
    this.Velocity_Y = 0;
    this.Width = width;
    this.Height = height;
    this.Gravity = 0;
    this.Weight = 0;

    this.isColliding = function (obj) {
        if (this.X > obj.X + obj.Width) return false;
        else if (this.X + this.Width < obj.X) return false;
        else if (this.Y > obj.Y + obj.Height) return false;
        else if (this.Y + this.Height < obj.Y) return false;
        else return true;
    };
}
</script>
</body>

```

However, I don't know how to program the canvas to rotate around its center, not the origin (Top Left corner). I know this has been asked and answered before on Stack Overflow, but I found it hard to understand the examples and I couldn't manage to apply them to my code successfully. When the A or D key is pressed, the canvas should rotate clockwise or counter clockwise from its center.

What would be the best way to achieve these things?

# Answer
The context has two functions relevant to this. There's `context.rotate(angle)` which you already know about, and then there's `context.translate(x,y)`. Here's a fiddle for it.

http://jsfiddle.net/awsumpwner27/k7CVw/

I also used `context.save()` and `context.restore()` which store the state of the context for convenience.
> 2 votes

---
Tags: javascript, rotation, html-canvas, html
---


# Question
Title: Bullet softbody nodes messed up positions
I recently switched from Havok physics to Bullet because I wanted to have soft body collisions, but I don't have any budget to license the (superior?) Havok solution, I couldn't even try those functions out there so it is completely new to me.
I want to create a soft body from an arbitrary mesh and for that I use the soft body helper:

```
btVector3* btVerts = new btVector3[vertices.size()];
for(int i=0;i<vertices.size();++i)
    btVerts[i] = (btVector3(vertices[i].pos.x,vertices[i].pos.y,vertices[i].pos.z));
const int iCount = indices.size();
const int tCount = iCount/3;
int* btInd = new int[iCount];
for(int i=0;i<iCount;++i){
    btInd[i] = (int)indices[i];
}

btSoftBody* softBody = btSoftBodyHelpers::CreateFromTriMesh(
        ((btSoftRigidDynamicsWorld*)dynamicsWorld)->getWorldInfo()
        ,(btScalar*)btVerts
        ,&btInd[0],tCount
        ,false
    );

```

Where `vertices` and `indices` are vector references coming from my graphics engine. I fill out the mesh with that information and seemingly I can create it without problem. After I step the physics world I connect my BULLET softbody nodes to my vertices in the graphics engine, then updating the vertex buffer.
I get the information from the softbody nodes by their `tNodeArray m_nodes` this way:

```
btSoftBody::tNodeArray&   nodes(softBody->m_nodes);

    for(int j=0;j<nodes.size();++j)
    {
        verticesIn[j].pos=XMFLOAT3(nodes[j].m_x.getX(),nodes[j].m_x.getY(),nodes[j].m_x.getZ());
        verticesIn[j].nor=XMFLOAT3(nodes[j].m_n.getX(),nodes[j].m_n.getY(),nodes[j].m_n.getZ());
    }

```

**The problem:** However I do not get correct vertex positions and neither correct normals. I am using a simple quad mesh with 4 vertices (the positions): **{ (-1,0,-1), (1,0,-1), (1,0,1), (-1,0,1) }**
But if I get values from the softbody's nodes after creation, but before stepping any physics I don't get back my original values from the nodes (the positions): **{ (-1,0,-1), (0,1,0), (-1,0,1), (0,1,0) }**
I even noticed the node vertices kind of resemble the originals, just "overlapped" somehow or not sure how can I describe if it is even the case, but it is like the second vector has an extra zero at the beginning and the whole mesh got screwed up.
Could it be something is not right with my loading? Or do I miss something in the concept of soft body physics?
I have studied the bullet soft body sample which is quite informative and they sure load their meshes like I do (the bunny mesh for instance), at least it seems like it. I don't have any idea and got stuck here for a day now. Without connecting to the softbody, my mesh remains correct.

# Answer
Ok it was a really stupid amateur mistake. I filled my btVerts array of btVector3 references whereas I should have done it for btScalars for every one of the three vertex position coordinates. The function even expects that, and I din't see it because copy-pasted from my mesh loading, where I send btVector3s as vertices in the btTriangleIndexVertexArray method (but I can specify the striding there, whereas in btSoftBodyHelpers::CreateFromTriMesh I cannot).
> 0 votes

---
Tags: bullet-physics
---


# Question
Title: How can I simulate shadows for a 2D top-down game?
I'm trying to simulate shadows for a 2D top-down RPG (in Python), but I can't think of the best way to do this

So far I've tried making copies of the original game entities and turning all opaque pixels black (which is a bit slow), then rotating them around the bottom of the original image... but i couldn't quite get that approach to work.

So how can I simulate this effect?

# Answer
> 0 votes
It´s all depending on how dynamic you want your game to be. If your sun positions is going to change constantly. then you need a more advanced approach.

But, in my opinion, your approach of having the original image and rotating it is good enough. You can do a basic "dynamic" shadow and you don't have to do a lot of overhead data for just shadows.

Then of course you somehow need to tag specific objects to cast and not to cast shadows.

There is also other solutions like a ray traced approach or a static shadow map. The ray traced approach is quite straight forward, you trace on the screen and when your ray find a "blocking" pixel, you break the ray and don't paint anymore "light". this will be the most awesome dynamic solution.

The static shadow map, is basically the same but you ray trace offline and save it into a texture. this wont be dynamic at all since you have to rebake every time the sun position changes.

---
Tags: 2d, rpg, pygame, shadows
---


# Question
Title: How do I manually control the lifetime of actor objects in C#?
I have the following `Actor` and `Scene` classes :

```
public class Actor
{
    string name;
    vec3   position;
    quat   rotation;

    public void Update()
    {
        ...
    }

    public void Render()
    {
        ...
    }
}

public class Scene
{
    List<Actor> actors = new List<Actor>();

    public void OnUpdate()
    {
        for (int i = 0; i < actors.Count; i++) {
            actors[i].Update();
        }
    }

    public void OnRender()
    {
        for (int i = 0; i < actors.Count; i++) {
            actors[i].Render();
        }
    }

    public void DestroyActor(Actor act)
    {
        actors.Remove(act);
    }
}

```

---

The `DestroyActor` method will remove a specified actor from the list, and stop it from updating/rendering, but it does not destroy it. Other actors still have a reference to that object, for example, the camera has reference to the player actor to chase him:

```
public class Camera
{
    Actor player;

    public void Update()
    {
        if (player == null) {
            // select nearest NPC and chase him
        } else {
            // chase player
        }
    }
}

```

---

I can change the classes and make them communicate via handles, for example, but that means I have to make the `Actor` class internal, instead of public, and include methods such as `ActorExists(int hdl)`, `GetActorPosition(int hdl)` and `GetActorRotation(int hdl)`. This makes me wonder what the difference is between C# and a low level language, like C.

In the Unity game engine, a call to `MonoBehaviour.Destroy(player)` will completely destroy the object, and set all references of that object to null. I know that they use the embed mono, and have more control over how the garbage collect works, but I wonder how do others work around these kind of problems in C#?

# Answer
> 1 votes
# Initial idea based off your Actor structure:

You are basically just wanting a character to be null, if you have removed it from the list that updates and renders it why not just set `act=null;` to handle resource disposing in `DestroyActor()` and track the resources themselves as part of your overall design. Otherwise these items will not be handled correctly and cause issues longer down the line. MonoBehaviours are handled behind the scenes and have a lot of code behind the simple `Destroy()` function, so it's not as simple as a one line solution:

```
public void DestroyActor(Actor act)
{
    actors.Remove(act);
    // Call the classes destroy to handle any resources to dispose manually.
    act.Destroy();
    act = null;
}

```

Garbage collection will cleanup any handled items so create a `Destroy()` or `Dispose()` function in your Actor class and clean up any resources used, GC will pick it up.

To expand you can keep references to your Camera within your Actor and break the references from there. Creating and calling a method such as `AttachedCamera.Detach();` could be easier to implement and then when removing the actor you would do:

```
public void DestroyActor(Actor act)
{
    actors.Remove(act);
    // Call on the referencing resources to detach from the actor.
    act.DetachResources();
}
...
//In Actor
public void DetachResources(){
    // Tell camera to detach
    attachedCamera.Detach();

    // Manage any other actors attached to this Actor
    foreach(Actor act in attachedActors){
        actor.Detach(this);
    }
}
...
//In Camera
public void Detach(){
    // Remove reference to actor
    _attachedActor = null;
}

```

# **Alternative (I would choose this):**

Use events and subscribing to listen when your actor is removed from the scene and get your attachable actors to then detach from it.

```
public class Actor
{
    string name;
    vec3   position;
    quat   rotation;

    public delegate void RemoveEventHandler();
    public event RemoveEventHandler Remove;

    protected virtual void OnRemove()
    {
        Remove();
    }

    public void Update()
    {
        ...
    }

    public void Render()
    {
        ...
    }
}

```

Listen to this event in your Camera:

```
public class Camera
{
    Actor player;

    // If player removed from scene, remove reference.
    private void ActorRemoved(){
        player.OnRemove -= new Actor.RemoveEventHandler(ActorRemoved);
        player = null;
    }

    public void Update()
    {
        // This is null if the above event is fired.
        if (player == null) {
            // Select nearest NPC and chase him.
            player = NearestNPC();
            player.OnRemove += new Actor.RemoveEventHandler(ActorRemoved);
        } else {
            // Chase player.
        }
    }
}

```

This then requires no tracking on the side of your player or NPC's and then you can assign the event to any necessary linked classes.

---
Tags: c#
---


# Question
Title: Designing codes on the top of a game engine requires special knowledges?
I am a web developer who works with C# and Ruby On Rails languages – it depends of the platform my customer have – and I don't need deep knowledge of medicine to create a portal based on it. By now, I want to jump-in unto game creation.

I don't want to create games from *literal* scratch: I want to create things on the top of game engines such as Unity or Unreal Engine. The point is: I need some physics or mathematics knowledge?

Yes, the basics that everybody knows it's essential I think, but advanced things is necessary? I mean, I need to be a doctor in physics to create awesome things with game engines? I know if I create a game engine, the knowledge is a little necessary, but remember: **I'll work on Unity or something like that**.

## Keep in mind...

* We are talking about to designing code. I'm not talking about to drag n' drop sprites and go;
* **I know** that a ***game engine*** is composed by some libraries that bring games to life, such as:

1. Audio services;
    2. Network tools;
    3. Graphics mechanisms;
* ... in other words, I know there are components that helps me to get things done, but I don't know if they do all the (hard?) work for me.
* I told you "\[...\] to create awesome things with game engines? \[...\]", do you remember? So, what you must understand by "awesome things" is: imagine a simple ball kicking the floor. OK, it moves up and down, and I want to do this applying gravity realities.

# Answer
You **don't** need a deep understanding of what the game engine does.

Otherwise there would be no point in using an engine. You need to understand *the overall picture* of what it does, and learn *how* to use it.

You also need to determine if the engine actually provides all that is required for your game (hint: it's probably not). E.g. let's say your game requires procedural generation of terrain: if the engine doesn't support it, you'll have to roll your own system for that.

In other words, something that an engine doesn't do for you is the gameplay layer. Everything that is specific to your game can't be part of an engine, by definition. So what you'll definitely need is knowledge of how to create games. Luckily, this is the kind of things you learn by doing them, so just delve into it and you'll be fine.
> 2 votes

---
Tags: architecture
---


# Question
Title: Is there any reason why there isn't a cross-platform implementation of DirectX?
Similar to how Mono can compile C# to various platforms, why isn't there an API that conforms to DirectX's specifications but can produce binaries for all platforms?

I understand that there is OpenGL but Microsoft is pushing DirectX with marketing and technologies such as XNA (which is now dead). Also, I understand that engines are supposed to support multiple backends (DirectX, OpenGL, Mantle, etc.) but that takes work..

# Answer
> 7 votes
> Similar to how Mono can compile C# to various platforms, why isn't there an API that conforms to DirectX's specifications but can produce binaries for all platforms?

First, I assume you mean something like an implementation of D3D that can be *compiled* on all platforms, since producing binaries that run on all platforms is not the domain of the graphics API (that's a language toolchain issue).

The answer is because nobody has written one. Strictly speaking, however, the Wine project and things like Transgaming's Cider have these sorts of emulation layers you are asking for, but they are not exposes as independent APIs.

Why hasn't anybody written one? Well, it's a lot of work and the reward is so small as to not be worth the effort. Unless such an implementation were done by hardware vendors, it would always be less efficient because it would necessitate wrapping one API in terms of another. Back around the time of the D3D10 release, there were a handful of projects (such as the "Alky Project," who main site appears to now be defunct) that tried to support D3D10 on older OSs like XP. They did this via OpenGL-based emulation of the D3D API calls, it just wasn't very good. I haven't looked at Valve's ToGL at all yet, but it's basically the same idea and consequently will always have that fundamental flaw.

Driver vendors have no particularly motivation to implement such a project *without* emulation, and they'd need to do it in cooperation with Microsoft (the D3D functional specification is not public), who *also* have no strong motivation to do so at this point. Given what AMD is doing with Mantle, it's possible that driver vendors want to trend *away*, at least in part, from providing standardized APIs and focus instead of investing effort in exposing ways developers can take advantage of their unique hardware capabilities.

Thus, any attempt at building such an API is only going to serve two real purposes:

* *It will let you use an API whose style you prefer*. But this is being done at the expense of performance and reliability (since emulating the specific behavior of all D3D calls for all possible inputs is very difficult, even when writing a D3D-to-D3D wrapper like SlimDX, which I used to be a part of) by introducing a competing abstraction. This means this would usually be a poor engineering basis for the selection of such a wrapper API.
* *It will assist in the porting of a game* written on Windows to another platform. Of course, so would using OpenGL from the get-go. We'll have to see what the upcoming D3D 12 adds to the table, but in general if you have any inkling that you might want cross-platform development in the future, you should probably stick to OpenGL. If you've already made the choice and invested in D3D, this can be a reasonable engineering rationale, but you still suffer the performance issue.

Essentially, anybody who has the capability of producing a good implementation of a D3D emulation layer would likely realize also that its use-case was basically limited to facilitating ports, which means adoption would be relatively low and it probably just isn't worth the effort for most people to consider building.

# Answer
> 0 votes
Well eventhough I doubt the usefulness of such project, DirectX and OpenGL implementations are not provided by the community, it is provided by the companies who make graphics hardware (Nvidia, AMD, Intel). And the *keyword here is **Business***...

So you will either wait for a software implementation of DirectX (or emulation on top of OpenGL), which limits its usefulness IMHO, or, wait for one of the companies to do that, and they won't'; for many reasons!

* It's not useful from their point of view, what revenue could such an involved project benefit them?
* OpenGL already exists and is already on par with DirectX.
* From their point of view they better provide an API that exposes more features/power of their hardware (e.g. AMD Mantle), it really makes sense from business point of view, rather than spending years developing a DirectX implementation that will probably be sub-par in the first years, won't help *Sell* more GPUs.

Even with cross platform DirectX, people will still optimize and even rewrite parts of the application for multiple platforms, it will be the same as the "cross platform" OpenGL which will you get different results on different platforms. I also suspect the big developers with already stable code bases will not switch as it gives them very little benefit.

Another interesting answer to read about the history of DirectX vs OpenGL.

---
Tags: opengl, directx, graphics
---


# Question
Title: How do I make a scrolling background out of a sequence of images?
I am new to AndEngine and trying to code a basic sidescroller game using the `ParallaxLayer` class from this example. (I followed the example and it works.)

How would I display multiple images sequentially? For example, I'd like 3 images (`Sun_Stage.png`, `Moon_Stage.png` and `Dark_stage.png`) to form the scrolling background. (First the background scrolls through `Sun_stage.png` then when it's finished scroll through `Moon_Stage.png`, et cetera.)

I basically just want to code a never-ending sidescroller with a changing scrolling background.

# Answer
I can't speak to using AndEngine, but the logic for an infinite scrolling backdrop is pretty engine-agnostic. Let's simplify and imagine the case where you are alternating between two images (it doesn't really matter how many you have).

Imagine a number line for x, from zero to infinity. Now imagine that your first image (image 0) is placed on that line such that its left edge (assuming you're scrolling right) is at `x = 0`. Its right hand edge will then be at `x = w0`, where `w0` is the width of image 0. Then your next image is placed so that its left edge is at `x = w0`, and its right edge is at `x = w0+w1`. Then the first image is placed so that its left edge is at `x = w0+w1` and its right edge is at `x = w0+w1+w0`. From the end of the second image on it repeats, and once you know `w` (the sum of w0 and w1; i.e. the combined width of all the images), you can figure out which image should be where without iteration.

This generalises to a simple function, which can say for any given `x`, what backdrop to use. That's because the answer for `x` is the same as `x modulus w`. You basically get:

```
function ImageAndOffsetFromPosition(x, out imageIndex, out offsetWithinImage)
{
    offsetFromLeftEdgeOfFirstImage = x % WidthOfAllImages();

    imageLeftEdge = 0;
    for (imageIndex = 0; imageIndex < imageCount; ++imageIndex)
    {
        imageRightEdge = imageLeftEdge + WidthOfImage(imageIndex);

        if ((offsetFromLeftEdge >= imageLeftEdge) && (offsetFromLeftEdge < imageRightEdge)
        {
            offsetWithinImage = offsetFromLeftEdge - imageLeftEdge;
            return;
        }

        imageLeftEdge = imageRightEdge; //Increment this so the next image is placed properly
    }

    //In theory you should never get here, because the position must lie within the range of all of the images
    // (because of the x % WidthOfAllImages() line).
    //In practice, you might get WidthOfAllImages() wrong, or you might ask for
    // the extreme right edge (x == WidthOfAllImages()).
    //So you should assert if you get to this point in the function.
}

```

This gives you, for any input position of x, what image should be underneath that position, and how far from the left of the image that position will be.

When you're scrolling to the right, what you're really doing is moving a sliding virtual window along this infinite number-line, so that at any given point in time, your camera is showing the region between `x = leftEdge` and `x = leftEdge + screenWidth`.

What you actually **need** is to know which backdrops are visible given your current camera position, and where they are relative to the screen. So you still need to iterate over the set of images you have, even once you know the starting position.

```
ImageAndOffsetFromPosition(cameraOffset, out leftmostImageIndex, out offsetWithinImage);

currentLeftEdge = -offsetWithinImage; //Shift the image partly to the left so that the part of it at the left screen edge is offsetWithImage pixels in. NB: this value is in screen relative co-ordinates, so 0 would be the left edge, -ve numbers are offscreen to the left, and +ve numbers are on-screen
currentImageIndex = leftmostImageIndex;

while (currentLeftEdge < screenWidth)
{
    Draw(currentImageIndex, currentLeftEdge);

    currentImageIndex = (currentImageIndex + 1) % imageCount;
    currentLeftEdge += WidthOfImage(currentImageIndex);
}

```

The only inputs into this section of code are the screen width and the cameraOffset. As you continually run right, cameraOffset will increase. To begin with, `leftmostImageIndex` will remain `0`, and `offsetWithinImage` will increase. Once `offsetWithinImage` reaches the width of the first image it will reset to 0, and `leftmostImageIndex` will increment. This pattern will repeat until you reach the right-hand edge of the last image in the set, at which point it will start again with 0 and 0. It can increase forever, and the modulus logic will make sure there are always images underneath the camera.

NB: this code will work even if the backdrop images are smaller than one screen in width, because it will loop and draw as many images as it needs to, even if they repeat, until it has moved past the right screen edge. If the backdrop images are larger than the screen width, then this loop will at most go round twice (when the boundary between images is on-screen), and usually only once.
> 3 votes

---
Tags: andengine, parallax-scrolling
---


# Question
Title: Rectangle touch sides of another rectangle
I am making a platformer game and im trying to make the player collide with all the blocks, here's a picture:

The blocks is stored in List and im trying to get the side's of the block usin

```
static class RectangleHelper
{
    public static bool TouchTopOf(this Rectangle r1, Rectangle r2)
    {
        return (r1.Bottom >= r2.Top &&
                r1.Bottom <= r2.Top + (r2.Height / 2) &&
                r1.Right >= r2.Left + r2.Width / 4 &&
                r1.Left <= r2.Right - r2.Width / 4);
    }

    public static bool TouchBottomOf(this Rectangle r1, Rectangle r2)
    {
        return (r1.Top >= r2.Bottom &&
                r1.Top <= r2.Bottom + (r2.Height / 2) &&
                r1.Right >= r2.Left + (r2.Width / 4) &&
                r1.Left <= r2.Right - (r2.Width / 4));
    }

    public static bool TouchLeftOf(this Rectangle r1, Rectangle r2)
    {
        return (r1.Right <= r2.Right &&
                r1.Right >= r2.Right - r2.Width  &&
                r1.Top <= r2.Bottom - (r2.Width / 4) &&
                r1.Bottom >= r2.Top + (r2.Width / 4));
    }

    public static bool TouchRightOf(this Rectangle r1, Rectangle r2)
    {

        return (r1.Right >= r2.Right &&
               r1.Right <= r2.Right + r2.Width &&
               r1.Top <= r2.Bottom - (r2.Width / 4) &&
               r1.Bottom >= r2.Top + (r2.Width / 4));
    }
}

```

I got this code from a Youtube video and i changed it a little bit.. (the original code didnt work well)

the problem im having is: the TouchBottomOf & TouchRightOf functions doesn't work well...(The collision occur randomly, sometimes on top of the block, sometimes little below it (TouchBottomOf), same with TouchRightOf)

Is there a better way to check it? thanks.

# Answer
This is a good way to check for overlap between two rectangles, but your code has a few bugs.

In the code you posted, the only function that works the way I would expect is TouchBottomOf. That function will return true if `r1` is overlapping the middle part of the bottom half `r2`.

`TouchTopOf` will return `true` when `r1` is above `r2` and NOT overlapping it (not touching it, but within 1/2 of `r2.Height`).

`TouchRightOf` and `TouchLeftOf` will never return `true`. Each of them requires `r1` to be both below `r2` and above it; This can never be true if your rectangles are more or less normal (Top \>= Bottom).
> 1 votes

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


# Question
Title: Collision detection circle-segment-segment
I've already implemented collision detection in my game loosely following this tutorial, which works great, but I realized there's one major flaw.
The player and the enemies are circles, while the obstacles can be either segments or polygons or circles.
Now, let's say I have `segment A` from `point (100, 100)` to `point (300, 100)` and `segment B` from `point (100, 200)` to `point (300, 100)`, which means they form an acute angle, and player has it center in `point (100, 125)`, with a radius of 25.
If player starts moving right, it will eventually collide against segment B. My method `checkCollisions()` will return a vector, but if I apply that vector on player, it will be moved up and left, and will overlap segment A.
If I call `checkCollisions()` a second time, player will be pushed down and collide again with segment B, so recursive invocations aren't a solution. Any ideas?

Here's a picture to explain: The g-\>n vector direction is along the bisector of the two little vectors, but how do I find the length?

# Answer
I think iterative solving may help.

The concept here is that you will solve several times each frame, but apply only part of the vector returned by `checkCollisions()` in each frame. The first solve attempt might start by applying the full collision response vector, because that will work fine in simple cases. If there are still intersections after that, you don't want to just bounce back to the original position. To avoid that, later iterations apply only a fraction of the response vector returned by `checkCollisions()`. To help the solution converge, the fraction is reduced for each iteration.

I know nothing about ActionScript, but here's some really terrible pseudo-code:

```
collisionResponseFactor = 1

for (i = 0; i < 20; ++i)
    responseVector = checkCollisions (player)
    player.position = player.position + responseVector * collisionResponseFactor
    collisionResponseFactor *= 0.8

```
> 1 votes

# Answer
You can just sum multiple collision response vectors. The contradictory elements will cancel each other out and the resulting vector will just be aimed out as expected. Remember to normalize and rescale by the correct magnitude after summing.

**EDIT (After OP added image):** To handle that particular problem, you have to find the unique position at which the circle is touching the line segment `AB` and `CD`.

You'll need to solve `A + (B-A) * t1 + r * n1 = C + (D-C) * t2 + r * n2` where the capital letters are the points in your diagram, `r` is the radius of the circle, `n1` is the unit length collision normal of the quadrilateral, `n2` is the same for the triangle, `t1` is a real value in \[0,1\] that represents "how far along" the vector `AB` the desired point of contact is and `t2` is the same for the vector `CD`. Only `t1` and `t2` are unknown and since everything except the `t`'s and `r` are vectors, we have 2 equations (one for x, one for y) in the unknowns. Once you solve for either `t`, you can plug in everything into the corresponding side of the equation above, which will give you the desired circle position.
> 0 votes

---
Tags: collision-detection, actionscript-3, separating-axis-theorem
---


# Question
Title: how to make a spritefont with multiple colors and black?
I want to make a multicolored font like:

My problem is that black is someway "set" as the transparency background for the font, so if i use black or any dark color xna takes it as background too.

How can i define in my spritefont what color is background and what not? is there a way to just draw my font with any program and use that as simple font?

# Answer
Based off Microsoft's help descriptor of the FontTextureProcessor class:

> Monochrome characters should use white for solid areas and black for transparent areas. To include multicolored characters, add an alpha channel to the bitmap and use that to control which parts of the character are solid.

Since you're editing the font as a BMP bitmap, it's not going to have a separate alpha channel. This is the reason that black or dark areas are being treated as transparent.

You'll need to edit it with software that supports an alpha channel such as GIMP or Photoshop, then export it to a PNG (with transparency enabled), TIFF, or any other such format with alpha support.

So let's take your original image:

So let's open it up in GIMP. The first thing is we need to separate the layers, the white has to go. To do this we need to select the "Fuzzy Select Tool":

Under the "Tools options" on the left, I would recommend setting the threshold to something around 100-150 for best results.

Now select the magneta background, and use CTRL+X to cut it. This should give us a white background with the letters still intact. Now we need to create a new layer:

Use CTRL+V to paste the magenta area into the new layer. Now use the Fuzzy Select Tool again to select the white areas, and delete them. I had to first right-click the layer on the right-hand side and choose "Add Alpha Channel" for this to work correctly.

Now in GIMP it should look similar to this:

Now we need to go to File -\> Export. Select the PNG type, and you should have a dialog that looks somewhat like this:

Those options I have selected should give the best results.

Now we get the result with proper alpha:

Note: I intentionally left out the white areas within the letters. That is left up as an exercise to the reader.
> 3 votes

# Answer
The reason that sprite fonts are white is so that you can apply your own color in the Spritebatch.DrawString. If I understand correctly, each pixel in your custom font will get multiplied by the `Color` parameter. If your source font sprite is black, you won't be able to apply your own color because black is all zeros.

If you want to make a custom font and render it black, leave the source white, then use `Color.Black` when you draw your string.
> -1 votes

---
Tags: xna
---


# Question
Title: How can I manage an animated UI from ActionScript?
I'm trying to code a game of Poker in AS3, using Flash Professional CS5 (although I try to keep as little code as possible in the .fla).

When a player bets, for example, I need to be able to show an animation of some chips sliding into the center of the screen. After that happens, the AI decides what to do, and another animation of their chips occurs. Then a menu pops up so the player can choose their own next action. And so on.

I started writing a `UIBet` interface with `bet(amount)` and `raise(amount)` methods and so on, that you would implement with a class extending MovieClip and fill in the methods with gotoAndPlays to various animations. But if I just have code that calls these graphics object like so:

```
playerUIBet.bet()
aiUIBet.bet()
menu.prompt()

```

Then, if I understand Flash correctly, what'll happen is that the code will finish executing, and then all of those animations will happen simultaneously.

How can I get these animations to happen sequentially? What if I want to insert pauses between them? Some kind of solution like this? What's the best way to do this in AS3?

# Answer
> 1 votes
There are multiple ways to address this problem, but my recommendation would be to use a tweening library like TweenLite. For simpler animations you can simply write the animations in code, and for other situations you can set delayed calls to functions using TweenLite.delayedCall()

---
Tags: flash, actionscript-3
---


# Question
Title: What is an axis aligned integer bounding box?
In this paper, in the **Distance field computation** section, it says that an axis aligned integer bounding box of a Prism has to be calculated. Can someone explain what an axis aligned integer bounding box is and how can it be calculated for a Prism?

# Answer
> 3 votes
An axis-aligned bounding box is a simplified representation of some object's volume and position. In this case, I think an axis aligned *integer* bounding box would be a bounding box that can only have integral dimensions, and an integral position.

If this definition is accurate, then a bounding box like this could be found if you found the highest vertex, representing the position of the top of the box, the lowest vertex in the prism representing the bottom of the box, most left vertex representing the left side of the box, and so on. Once you had all coordinates you'd need to make them integers, so you'd "round away" from the centre of the prism, like how you can round away from zero. This is so the box's sides don't intersect with the prism, and the prism is contained within the box.

---
Tags: mathematics, bounding-boxes, computational-geometry
---


title: (WebGL) Point light per-fragment issue

text:
# Question
Title: (WebGL) Point light per-fragment issue
I'm using an FPS-like camera, this is the code:

**CAMERA**

```
mat4.identity(mat.mvMatrix);
mat4.rotate(mat.mvMatrix,degToRad(-camera.pitch),[1,0,0]);
mat4.rotate(mat.mvMatrix,degToRad(-camera.yaw),[0,1,0]);
mat4.translate(mat.mvMatrix,[-camera.pos[0],-camera.pos[1],-camera.pos[2]]);

```

The above code produces the *model-view matrix* as i roam the map (handling the camera position via *WSAD* style keys) The `uMVMatrix` from vertex shader is the passed `mat.mvMatrix` from the above code.

I'm also using a shader for *point lighting per-fragment* in WebGL, the fragments are:

**VS**

```
vPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
gl_Position = uPMatrix * vPosition;
vTransformedNormal = uNMatrix * aVertexNormal;
// pass to fragment shader
vColorLight = uColorLight;
vColorAmbient = uColorAmbient;
vLightPosition = uLightPosition;

```

**FS**

```
vec3 lightDirection = normalize(vLightPosition - vPosition.xyz);
float directionalLightWeighting = max(dot(normalize(vTransformedNormal), lightDirection), 0.0);
vec3 lightWeighting = vColorAmbient + vColorLight * directionalLightWeighting;
vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
gl_FragColor = vec4(textureColor.rgb * lightWeighting, textureColor.a);

```

The `vLightPosition` is actually the camera's position (the light position moves as i move around) I don't have a problem by moving around and putting correctly transformed objects. But my lighting position seems to *run away from me* (i can't describe it better) as i roam the map. At position *\[0,0,0\]* is good, but as i move from there i can see actually the light source goes far away, and actually *sinking* (although i'm not changing my height =Y position)

Surprisingly, i solved the above problem by multiplying the input `vLightPosition` by **0.00054687** (!) before i send it to shader, where it gave me a centered bulb in the terrain. I post 2 images to illustrate this:

*When i multiply my light position by the above number..*.

```
var lightPosition = [5,2,5];   // just example
gl.uniform3f(gl.getUniformLocation(program,"uLightPosition"),
             parseFloat(lightPosition[0])*0.00054687,
             parseFloat(lightPosition[1])*0.00054687,
             parseFloat(lightPosition[2])*0.00054687);

```

*When i'm passing light position directly as camera position..*

```
var lightPosition = [5,2,5];   // just example
gl.uniform3f(gl.getUniformLocation(program,"uLightPosition"),
             parseFloat(lightPosition[0]),
             parseFloat(lightPosition[1]),
             parseFloat(lightPosition[2]));

```

In fact you can hardly see a light source that comes from far, far away (stones are lit).

It seems i need to *scale down my input light position to microscope level*, yet i dont understand why and though i solved it mostly by luck, i would like to know where's the problem to prevent future issues. Thanx

**EDIT**

My full shader fragments:

**VS**

```
precision mediump float;

attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;

// lighting
uniform int uLightType;
// general
uniform vec3 uColorAmbient;
uniform vec3 uColorLight;
// directional light
uniform vec3 uLightDirection;
// point light
uniform vec3 uLightPosition;

varying vec3 vTransformedNormal;
varying vec4 vPosition;

// lighting on fragment shader
varying vec3 vColorAmbient;
varying vec3 vColorLight;
varying vec3 vLightPosition;

varying vec2 vTextureCoord;
varying vec3 vLightWeighting;

void main(void) {
    vTextureCoord = aTextureCoord;
    // none light
    if (uLightType==0) {
       gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
       vLightWeighting = vec3(1.0, 1.0, 1.0);
    }
    // directional light
    else if (uLightType==1) {
       gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
       vec3 transformedNormal = uNMatrix * aVertexNormal;
       float directionalLightWeighting = max(dot(transformedNormal, uLightDirection), 0.0);
       vLightWeighting = uColorAmbient + uColorLight * directionalLightWeighting;
    }
    // point light (per-fragment)
    else if (uLightType==2) {
       vPosition = uMVMatrix * vec4(aVertexPosition, 1.0);
       gl_Position = uPMatrix * vPosition;
       vTransformedNormal = uNMatrix * aVertexNormal;
       // pass to fragment shader
       vColorLight = uColorLight;
       vColorAmbient = uColorAmbient;

       vLightPosition = uLightPosition;
       //      vLightPosition = uMVMatrix * uLightPosition;
       //      vLightPosition = uMVMatrix * vec4(uLightPosition, 1.0);
       //      vLightPosition = (uMVMatrix * uLightPosition).xyz;
               vLightPosition = (uMVMatrix * vec4(uLightPosition, 1.0)).xyz;

    }
 }

```

**FS**

```
precision mediump float;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
uniform sampler2D uTex0;

uniform int fLightType;
varying vec4 vPosition;
varying vec3 vTransformedNormal;
// lighting
varying vec3 vColorAmbient;
varying vec3 vColorLight;
varying vec3 vLightPosition;

void main(void) {
   // point light (per-fragment)
   if (fLightType==2) {
      vec3 lightDirection = normalize(vLightPosition - vPosition.xyz);

      float directionalLightWeighting = max(dot(normalize(vTransformedNormal), lightDirection), 0.0);

      vec3 lightWeighting = vColorAmbient + vColorLight * directionalLightWeighting;
      vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
      gl_FragColor = vec4(textureColor.rgb * lightWeighting, textureColor.a);
   }
   else {
      vec4 textureColor = texture2D(uTex0, vec2(vTextureCoord.s, vTextureCoord.t));
      gl_FragColor = vec4(textureColor.rgb * vLightWeighting, textureColor.a);

   }
}

```

**EDIT2**

# Answer
> 0 votes
```
vec3 lightDirection = normalize(vLightPosition - vPosition.xyz);

```

`vPosition` is in view/camera space, `vLightPosition` is in world space, hence the buggy results.

You need to transform your light from world coordinates to view coordinates, i.e. multiply the light coordinates by the view matrix (just as you multiplied the position by the model-view matrix).

---
Tags: javascript, glsl, webgl
---


# Question
Title: When entities don't draw themselves, who actually does?
There are countless questions here about whether entities should draw themselves or not. The answer is almost universally *no, there should be a renderer*. And I do see a point in having a single place where everything is rendered. Makes asset management easier and the code less convoluted.

However, I'm struggling to find a good approach to implement this in my 2D game. Currently, every entity is told to draw itself, and I pass the renderer object to it. Now, I want the renderer to draw each entity, but I don't want the renderer to actually know about entities, so I need a more generic class, e.g. `RenderObject`, and a way to construct render objects from entities.

One obvious approach would be to have a `GetRenderObject()` method on each entity. However, some of my entities actually draw multiple textures, relative to their position, so I'd probably need a `GetRenderObjects()` function instead.

But that wouldn't really remove any rendering logic from my entities. I'd still have to refer particular assets and their positions relative to the entity position in the render objects I create.

So my question is: Doesn't having a renderer mean that my entities don't have any drawing logic anymore? If so, who will generate these render objects? Does it even make sense to take the render objects detour?

And, bonus question: How can this work together with a UI system? I'd rather not have the renderer know about widgets and containers and such, so my hunch so far is to have widgets stick to drawing themselves.

# Answer
> 1 votes
Remember that the point of "entities should not draw themselves" is to remove the dependency on the renderer from the entity system and to allow render logic to be factored out into a few places as possible. Both increase quality the code through improved maintainability and decreased coupling.

A `RenderObject` class is a good approach, however, if the entity itself generates it, you're still in the domain where the entity "knows things" about how to render objects. There is no difference between an entity that takes a renderer and says "renderer, put a textured quad *here*" and one that has a function that returns an object saying "renderer, draw a textured quad *there*."

Instead, remember that non-member functions increase encapsulation and move that logic for assembling a render object for a given entity out to a level of abstraction that *already* knows about both the entity system and the renderer: the game itself. This way there is no loss of generality. The "game" object is *already* the thing that ties all your various disparate systems together.

At a high level, in other words, your game loop might contain something like this:

```
var renderables = new List<RenderObject>();
foreach (entity in the world) {
  // Perhaps cache instead of reconstruct here, if your specific
  // render object is "expensive" to build:
  var renderable = CreateRenderObjectForEntity(entity);
  renderables.Add(renderable);
}

renderer.RenderAll(renderables);

```

`CreateRenderObjectForEntity` is a method that exists on the game object itself, or some system at a similar layer of abstraction, and it's sole job is to take an entity, extract useful bits of information about it, and turn that into a `RenderObject` (or multiple render objects, if that's needed).

An entity's position data is certainly useful for things beyond rendering, so it can remain in the entity. Things like texture *references* (as in, just strings or IDs) aren't actually render-API objects and so they *could* remain in the entity, particularly if you are using a component-based approach to entity construction that is so popular these days: an "aspect" or "visual" component can be added that holds all the render-only data like texture or shader references. If you don't have a component-based system, you can still offload some of that information to external databases. For example, an entity could have a "race" and "gender" like in most RPGs, and the you can actually look up the texture ID reference in some catalog of race/gender combinations you load from one of your data files.

This approach scales naturally to user interface: user interface is another system that you fit an adapter in front of to create render objects for all the appropriate screen / widget elements in the current scene.

---
Tags: architecture, graphics, rendering
---


title: Unity Property inspector glitched?

text:
# Question
Title: Unity Property inspector glitched?
I just updated my Unity from 4.3.3 to 4.3.4 and there is something very wrong with the Property Inspector window. I tried restarting Unity, as well as load a different project, but neither fixed it.

This is what it looks like with a shader selected:

Even an empty folder looks corrupt:

Is this a known issue and is there a way to fix this?
Update1: I did a complete reinstall of 4.3.3 and the problem remained, now I am really confused.

# Answer
> 2 votes
Running Unity in DX11 mode solves the issue. It can be done by adding "-force-d3d11" at the end of the target field in shortcut properties. It fixes the issue, along with some others, on Intel HD4xxx iGPU's.

---
Tags: unity
---


# Question
Title: Using uniform grids for collision detection - Efficient way to keep track of what a cell contains
I was looking for an efficient way to implement collision detection in a 2D game. A way that won't result in an O(n^2) level of complexity.

A lot of people recommend to use Uniform Grids for this purpose. From what I gather, this means (please confirm if this is accurate):

* Dividing the screen to a grid of equally sized square areas. Each area is represented by a 'cell' inside a 2d array.
* Each cell is a data structure such as a List, or an object containing such a data structure.
* The cell contains references to all of the game objects that overlap with the area the cell represents (objects 'inside' the cell).

Each update step, every object in a cell is checked for collision with every other object in the same cell.

I understand all of this. But one thing is still not clear to me:

**Every update step, I need to check if any game object left the cell it was inside of and moved to another cell. I always need to know which object is in what cell.**

The only idea I had of how to do this, is each update step: 1- clear all of the cells. 2- Reassign all the objects to the cells.

Meaning: If I have 40 cells and 70 game objects on screen, every object of 70 is going to have to go through 40 `if` statements:

```
if (object overlaps area 1) put it in cell 1;

if (object overlaps area 2) put it in cell 2;

... // until 40

```

**My question: Using 40 `if` statements (or a big `switch`) *for every object* isn't reasonable. Please suggest a more efficient way to keep track of what objects are in what cells.**

Thank you for your help, will be appreciated.

# Answer
> Each cell is a data structure such as a List, or an object containing such a data structure.

AFAIK this is not the way how it is usually implemented. This way you will waste lot of memory for arrays or lists, and lot of CPU cycles for manipulating them. For example, 32x32 grid will result in 1024 arrays/lists, and this will be especially bad with non-contigious memory layout (like with linked lists).

Instead, on every physics step every moved entity gets new **spatial mask** (I am assuming all still entities already have it). Every row and every column of grid are representing one bit of spatial mask. If object's bounds are lying in given row or given cell, then corresponding bit in object's spatial mask is 1, otherwise it is 0.

Then simply binary `and` of their spatial masks used to check whether objects are either *surely-not colliding* or *may-be-colliding*. On latter, you need then check collision with precise algorythm.

Algoriths example:

* Prepare spatial mask. For each entity:

+ Erase spatial mask.
    + Calculate `AABB`.
    + Detect span of rows and columns in which object's bounds are lying.
    + Enable respective bits of spatial mask.
* Find collisions. For each pair of entities:

+ Skip, if their spatial masks are not "intersecting" (`and` them).
    + Skip, if they are not colliding.
    + Gotcha.

You can pack both axes into one integer value, this way you will get 16x16 or 32x32 grid (on 32-bit and 64-bit systems respectively), I think it is precise enough for most situations and fast.

Also, if you have massive amounts of static geometry in your levels, I'd recommend building BSP-tree for it, and then using spatial masks only for dynamic objects.

See also: separating axis theorem.
> 4 votes

# Answer
The simple approach is just this: Each entity remembers what cells it is in.

Each time the entity moves (or rotates or changes size or etc), check whether the cells it is in post-moving are the same as the cells it was in before moving. If the pre-move cells are the same as the post-move cells, do nothing. If there are any differences, update the grid by removing this particular entity from the old cells, and then adding it to the new ones. For bonus points, only remove the entity from the cells which it used to be in but isn't now, and only add it to the cells which it wasn't in before, but is now.

In most games, many entities will tend to remain stationary, and so doing the processing only when an entity moves (rather than always for every entity at the end of every update) will automatically avoid performing this unnecessary logic for stationary entities.
> 4 votes

# Answer
There are some subtle implementation tips and tricks to resolve this:

1. We aren't talking about regular lists. These lists's node elements each contain a time record of the last (discrete) time it was changed. This is normally the frames index. We'll call it a time stamp.
2. When you add an object to a cell's list, you first look at the list's items. If the first node has has an outdated time record, you can discard it or overwrite it at this time.
3. If the existing nodes time stamp is current then you need to check for collision against that node's object and then move to the next node on the list.
4. If the next node is current, go to (3), else go to (2).

Feel welcome to comment if you have questions.

If an object isn't moving often (or not at all), it should be handled differently. If it's not moving at all, the time stamp should be unique to identify that (for instance -1). If it's moving rarely it would be easier to handle like @Trevor Powell suggested in his answer. By keeping a collection of pointers to the cells it's currently inhabiting, and updating these cells when it actually moves.
> 1 votes

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


# Question
Title: 3D position to UV coordinates in fragment shader
I am interested in converting an arbitrary 3D position computed at run time in the fragment shader to its corresponding UV coordinates. Notice that the 3D position I am interested in is NOT a 3D vertex present in the VBO, but an arbitrary 3D location that may lay somewhere inside one of the triangles of the mesh.

What is the best way to perform this 3D to UV mapping? I am thinking of looking at the vertices of the face where the 3D point is, and interpolate its UV coordinates using the distance between the 3D point and the 3D vertices as a weights, but I have a feeling I may be overthinking this problem.

Ideally, I want to do it in a GLSL fragment shader. Does any body have any suggestion, example code, or better idea to solve this problem?

# Answer
> 3 votes
Do you know which triangle the point is in, and do you have access to the vertex data for that triangle (namely positions and UVs)? If so, this is a fairly simple problem, and is doable in the fragment shader on powerful enough hardware (it's going to be too math-heavy for mobile devices, most likely).

If you don't know which triangle to use, you have to figure that out first - which makes the problem a lot more complicated, and probably not something you can reasonably do in a fragment shader if there are more than a handful of triangles.

However, assuming you know which triangle you're in, here's how you'd do it. I won't write out the code explicitly, assuming you can fill in the details yourself.

1. Find the barycentric coordinates of the point, with respect to the triangle. These are essentially distances to each edge, but remapped to the \[0, 1\] range so that the coordinate is 1 at the edge and 0 at the opposing vertex. You can do it by calculating the plane equation for a plane perpendicular to the edge (use the cross product of the triangle's normal with the edge vector), then calculate the point's distance from that plane, then scale and remap it based on the opposing vertex's distance from the plane. Do this for each edge.
2. Use the barycentric coordinates to interpolate the vertex UVs. This takes the form of

```
finalUV = UV0*bary0 + UV1*bary1 + UV2*bary2

```

where `UV0, UV1, UV2` are the vertex UVs and `bary0, bary1, bary2` are the barycentric coordinates for each vertex (derived from the distance to the opposing edge as seen in step 1).

# Answer
> 0 votes
Your problem seems trivial, so maybe I'm missing something.

As you say that you want to compute the UVs for each fragment, I'm assuming that you are interested in the UVs of the fragment itself.

Are you assigning UVs to your vertices or are computing them procedurally?

In the first case, you will need to assign the UVs of each vertex in a varying variable. The hardware will automatically interpolate it's value for each fragment based on its barycentric coordinates and the interpolation mode. In the latter case, calculate the UVs in the vertex shader and assign the result to a varying variable in order to receive an interpolated value again in the fragment shader.

---
Tags: opengl, glsl, 3d-meshes, fragment-shader, uv-mapping
---


title: Unity animations in iOS

text:
# Question
Title: Unity animations in iOS
I'm an iOS developer and I'm trying to make 2d animations with Unity 4.3 + RageTools Pro + RageSpline. I want to integrate the animations into a native iOS application. In Unity I have different kind of animations, different characters, and I want to control these separately in Xcode.

I know how to build unity project to Xcode and I know how to customize the Unity view in Xcode, my problem is that I can't access individually the animations, I can't loop them and I can't switch them in a specific view. My another problem is that the built Xcode project from Unity is too large (more than 300 MB).

So the question is if I continue to develop the character animation within unity is it possible to handle separately the animations in Xcode? Or do I have to find a another solution (use another animation tool, or export from unity into some different file format like FBX). In summary I want to make a simple iOS app with simple animations and i'm looking for the simplest solution.

Thanks in advance for your help.

# Answer
> 1 votes
I can't comment on the use of RageTools, but some notes on keeping things simple:

* Unity can import animations that were exported in FBX format. This is a fairly typical use case - you make your models elsewhere and animate them, and bring those animations into Unity. You can switch between FBX animations being used just fine using the Unity Animation components. The only thing you can't effectively do is add animation events, that has to be done inside Unity, on internal Unity animations. You can also animate models in Unity directly from the animation editor there.
* When you're building things with Unity, most of the time you should not be worrying about XCode at all. All of your editing and scripting will be done in Unity and MonoDevelop. There are times when you need to write custom iOS code, which can only be done in XCode, but those are really just edge cases and pretty rare, for simple games.
* The size of the XCode project is irrelevant. The only size that matters is the size of the output iOS build (the .ipa file). The size of that, above a certain base level which comes from using Unity (the DLLs and code size), is massively dominated by your assets. Image assets can be very large, and every image asset referenced in your scenes will be included in the build (even if they're not visible). However for iOS you would ideall not be using uncompressed (Truecolour or 16-bit) images; you should be changing the image properties in Unity to set those images to be compressed (at whatever quality level you feel is sufficient for your game). Image size and efficiency is one of the biggest factors for mobile games - because not only will it make your build large, it will run out of memory very quickly. No engine can magically fix that for you, it's something you need to take into account when you are building the assets for your game. Re-use images as much as you can, avoid wasted space (e.g. large images where a lot of the image space is actually transparent), limit the amount of distinct images needed in any given area of your game, and ask Unity to compress the images wherever possible.

---
Tags: unity, animation, ios
---


title: Rendering terrain only with GPU

text:
# Question
Title: Rendering terrain only with GPU
This is not about generating plane geometry and then applying a shader on it. Instead, I want a big single flat plane, then apply a shader on it.

The vertex shader has a `uniform vec3 realPlanePosition` and calls a height calculation function:

```
// Vertex shader code

uniform vec3 realPlanePosition;

varying vPosition;

float heightCalculation(vec2 verticePosition) {
    // Just for pseudo-code (more black magic append here).
    return magicNoise2D(verticePosition.x, verticePosition.y);
}

void main(void) {
    vec3 vPosition = position;
    vec2 verticePosition = vec2(vPosition.x + realPlanePosition.x,
                                vPosition.y - realPlanePosition.z);

    vPosition.z = heightCalculation(verticePosition);

    gl_Position = projectionMatrix * modelViewMatrix * vec4(vPosition, 1.0);
}

```

In my plane update code, I just change `realPlanePosition` with player position, for example. The plane moves on `(x, z) (X rotation: -PI/2.0)`. The only thing the vertex shader updates is the `z (due to plane rotation)` value of `gl_Position`.

Is this good practice? Also, how do I detect collisions with it? And finally, how can I control other terrain objects' generation (rocks, trees, ...)

# Answer
This is usually a bad idea if you want the terrain to be interactive. And even if you don't, rendering the noise to a texture first will save you a lot of noise sampling. Collisions and other stuff is usually done on the CPU, so you'd be generating the terrain twice.

So it's great for backdrop terrain (or "far" LOD version of the terrain, assuming you don't need the terrain for some other reason), but not so good when you want a terrain to walk on. Adding things like rocks and trees is basically just doing the same thing again - which is also a lot easier if you have the map in a texture.

Since you're generating a heightmap anyway, there's very little to gain from generating the terrain only on the GPU (note that it might be worth it to generate parts of the terrain only on the GPU, such as close-up detail geometry).

Now, if you generated a 3D terrain (not just a plain heightmap), that's a wholly different beast, but in the end, you'd probably pre-render it somehow anyway. Unless you're doing this for a demo, purely-GPU terrain probably isn't very useful.
> 0 votes

# Answer
You don't want todo this every frame. Use either transform feedback or the CPU to calculate it once, then store in a VBO. If you want a large world then divide it into chunks as needed.

Also since the grid is fixed, as the noise 'moves through' the grid, the terrain will wobble around, if using low poly count for the terrain then this would be very dramatic and nauseating.

I don't even see how this relates to collision detection.
> 2 votes

---
Tags: shaders, terrain, vertex
---


title: Looking for XNA patterns

text:
# Question
Title: Looking for XNA patterns
Hello mature game developers. Im just started with XNA, but i got solid expirence with C#. I wonder is there any common code patterns for XNA games?

Like should i make classes wich handle draw and update separatly, like draw model and world data model? Or should i try to put as much code as possible in Game1 ?

Im totaly lost in project structure building. Thx for any answers.

# Answer
The MVC architecture doesn't work so great for games. Typically games use a very simple one-to-one OOP architecture where game objects typically have methods like `Update` and `Draw`.

In the cases where an MVC architecture would seem useful - often in networking scenarios - you usually just go the simple route with the OOP `Update`/`Draw` model, implemented in such a way that if `Draw` is never called, it doesn't matter.

(This can be tricky with "retained mode" APIs, but XNA is "immediate mode", so it's less of an issue.)

In game development, it's very unusual to be in a situation where you need to support multiple views on a model, where the views are substantially different enough that you need architectural support.

One place you often see an MVC-*like* architecture is in board- and card-games. These scenarios can often look very much like functional-programming. Where you have a (usually immutable) game-state and methods for advancing that state to generate a new one. The big reason for using an architecture like this is for AI.

(And *still*, in these cases, you can easily just implement `Draw` methods on your game state that don't care whether they get called or not.)

In all of these scenarios, there's not much built in to XNA to help you. You have to build everything yourself, starting from the given `Draw` and `Update` and other methods in `Game`. (There's `DrawableGameComponent`, but that gets you very little that you couldn't trivially do yourself, while limiting what you can do, so I generally recommend against using it.)

Finally, as I mentioned in comments, I've got a very popular answer on game architecture over on Stack Overflow.
> 2 votes

---
Tags: xna, c#, patterns
---


title: Stop schedule on gameOver

text:
# Question
Title: Stop schedule on gameOver
I have 2 events running through time in my game. I want that when gameover starts, this events stops running

This is my code:

```
- (void)onEnter
{
   [super onEnter];
   [self schedule:@selector(addStars:) interval:1.5];
   [self schedule:@selector(addBoxes:) interval:2.5];

}

-(void)gameOver
{

 //stop schedule addStars
 //stop schedule addBoxes

 }

```

# Answer
> -1 votes
Man, Just do this bellow:

```
-(void)gameOver
{
   [self unschedule:@selector(addStars:)];
   [self unschedule:@selector(addBoxes:)];
}

```

---
Tags: cocos2d-iphone
---


# Question
Title: Maintaining velocity of free fall body using Box2D in libGDX
I want to maintain the speed of a free-falling Box2D body using LibGDX. I'd like the vertical velocity increase with the level. I've applied a linear impulse and velocity actually increases like this:

```
fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);

```

I think this is a bad approach, because the speed has increased only a little and I applied as much as -800 units of impulse.

Below is my render function of game play screen class:

```
    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

//      camera.update();
//      batch.setProjectionMatrix(camera.combined);
        batch.begin();

        backgroundSprite.draw(batch);
        grassSprite.draw(batch);

//      bucketSprite.draw(batch);

        Iterator<Body> bodies = world.getBodies();

        while(bodies.hasNext()){

            Body body = bodies.next();

            if(body.getUserData() != null){

                String spriteName = (String) body.getUserData();

                Sprite sprite = (Sprite) userDataMap.get(spriteName);

                if(spriteName.equals("bucket"))
                    sprite.setPosition(body.getPosition().x + 345, body.getPosition().y + 230);
                else
                    sprite.setPosition(body.getPosition().x + 375, body.getPosition().y + 225);

                sprite.draw(batch);

            }
        }

        batch.end();

        fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);
//      debugRenderer.render(world, camera.combined);
        world.step(1/60f, 8, 3);
//      world.clearForces();
    }

```

My world is:

```
world = new World(new Vector2(0, -10), true);

```

Orthographic camera:

```
camera = new OrthographicCamera(800, 480);

```

My fruitBody fixture def is:

```
bodyDef.type = BodyType.DynamicBody;
        bodyDef.position.set(0, 100);

        // shape
        CircleShape ballShape = new CircleShape();
        ballShape.setRadius(15f);

        //fixture
        fixtureDef.friction = .1f;
        fixtureDef.restitution = .7f;
        fixtureDef.shape = ballShape;
        fixtureDef.density = .2f;

        fruitBody = world.createBody(bodyDef);
//      fruitBody.setUserData(fruitSprite);
        fruitBody.setUserData("fruit");
        fruitBody.createFixture(fixtureDef);

```

I just want to increase the fruit's speed (free falling body) at each level by a given value.

# Answer
> 6 votes
*Disclaimer: I have not used libgdx or Java before, this answer borrows syntax from the question and official documentation, and the code is untested*

To make the bodies 'fall' under the influence of gravity in box2d, you must first pass a non-zero gravity vector to the `b2World` when constructing the world

```
World world = new World(new Vector2(0, -10), true);

```

This means that every time `World::step` is called the gravitational force will be applied to every `DynamicBody` and the velocity will be updated accordingly.

# Drag Force

This is all well and good if all you want is constant acceleration, without any opposing forces. To add a little realism we would like to add a drag force to simulate air resistance. I know there are a lot of resources out there explaining how air drag works, and the wikipedia article is the obvious starting point.

In a nutshell, the magnitude of the drag force is most frequently modelled like this:

Whenever you encounter a new formula like this, I find the best way to get an understanding of it is to see what happens when specific variables are set to zero, become negative, or take on large values.

In this case I just want to consider what happens to the drag force when the velocity, v, changes and all other parameters are set to positive, real values.

* If v -\> 0 then Fd will also tend to zero.
* If v \>\> 0 then Fd will take on a large positive value.
* If v \<\< 0 then Fd will take on a large positive value.

Notice Fd will never be negative. This is an important feature.

The *direction* of the drag force is frequently assumed to be opposite to the velocity vector. This is a simple assumption that is easy to implement and unconditionally stable in code.

So if our fruit is falling (accelerating) under the influence of gravity it's gaining speed. But while that's happening the drag force must be increasing because the velocity magnitude is increasing. The drag force will continue to increase until terminal velocity is reached.

Terminal velocity is the point at which the drag force is equal in magnitude and opposite in direction to the gravity force. If the forces are equal, the *acceleration* of the fruit must be zero, and the velocity of the fruit which satisfies this condition is the terminal velocity.

You can even determine what the terminal velocity must be at the outset if you set Fd = Fg and solve for v.

## Implementation

This is great in theory, but how can we implement this in code?

box2d does not provide any built-in features to implement drag, so we have to do it ourselves.

To do this we need to get all the bodies and cycle through them at each time step, calling `Body::applyForceToCenter` on each one. I'm going to borrow the code from your rendering function as an example.

```
Iterator<Body> bodies = world.getBodies();

//This constant H is the lump constant of 1/2*rho*Cd*A from the wikipedia formula
//Play with this parameter to get the results you want
float H = 0.5;

while(bodies.hasNext()){

   Body body = bodies.next();

   Vector2 v = body.getLinearVelocity();

   //Get the square of the velocity by computing the square of the distance from the origin
   float vSqrd = v.dst2(Vector2());

   //Calculate the magnitude of the drag force
   float fMag = H*vSqrd;

   //Calculate the drag force vector to apply
   //We do this by taking the norm of the velocity and negating it to get the direction.
   //That vector is multiplied by the magnitude to get the drag force we want to apply
   Vector2 fd = -v.norm()*fMag;

   //Finally we communicate this to box2d by calling applyForceToCenter
   body.applyForceToCenter(fd);

   }

```

That should be it. I don't have anything setup right now to run that code, but that is the is the general idea. I judged from your language that you were having more trouble understanding the physics than the code, which is why I expounded on that first.

As a side note applying linear impulses at every time step can produce some funky results because it applies the same impulse regardless of the timestep size (which can vary) whereas applying a force takes into account the timestep size.

---
Tags: java, libgdx, box2d, body
---


# Question
Title: How do I inline images between text in a Table?
I have a `Table` and a `Label` with wrapped text. I want to display some images in-line with the text. For example:

> This is an image -IMAGE\_HERE-, and now some more text showing, yet, another image -IMAGE\_HERE-.

I tried using one `Label` containing all the text and spaces for the images, then draw the sprites. However, I can't get the locations I should draw the sprite in to fill those spaces. I could hard-code the values, but they'll vary per device. I also tried adding multiple labels with images between, but that didn't work out either.

Is there a way of fixing this, say by calculating words' widths? Is it possible to have text with inline images in a `Table`?

---

if you are wondering why I'm using a `Table`: The `Label` text should fit on screen regardless of device resolution. I've found a `Table` helps with this: I just set `bounds` and `size` and it works.

# Answer
I couldn't find any help with my issue so I resorted to adding multiple `Labels` and using the `Label`'s `X`, `Y`, `width` and `height` to set the position of the `Sprite`.

I also require an animation which I don't think is possible in a `Table`, so I will have to just do this.

Thanks for your help.
> 1 votes

# Answer
Use an `Image` instance instead of `Sprite` because `Image` extends `Actor` and can be added to a `Table` as an individual actor.
Then split the content to be displayed on your screen into four pieces: one for the first bit of text, one for the first `Image`, one for the second bit of text, and the last for the second `Image`.
Add these actors to different cells in the same row in the table:

```
table.add(label1);
table.add(image1);
table.add(label2);
table.add(image2);

```

You can then play with various layout/spacing/sizing effects in the table as you see fit for your case. Just type in `"."` on the `add(actor)` method and then hit `Ctrl + Space` to see what functionality it provides.

You might also want to check out the following link which provides a pretty nice description of the `TableLayout`: TableLayout.

Hope this helps.
> 2 votes

---
Tags: java, android, libgdx, eclipse
---


title: Unity3D animation trigger reset

text:
# Question
Title: Unity3D animation trigger reset
How can I reset conditions for animations using an animation controller?

I have a door that will open when a boolean property in a script is set to true. This then calls setTrigger on the animator to play the open door condition and then reset the boolean property to false. After 5 seconds I then close the door. However when I change the boolean to true again to open the door, either the setTrigger isn't working again on the animator, or the trigger for the door close is conflicting. How would I resolve this? Is there a way in the animator to set a condition to false when a particular animation has finished? Initially I was using a boolean condition in the animator but ran into the same problem. I looked at the 2D sample project which used trigger instead and assumed this would only fire once. However I guess something else could be wrong. The code in my script is as follows: (where anim is the animator component)

```
   void Update(){
    if (open) {
        OpenDoor();
        open = false;
    }
}

void OpenDoor(){
    anim.SetTrigger ("OpenDoor");
    Invoke("CloseDoor",5);
}

void CloseDoor(){
    anim.SetTrigger ("CloseDoor");

}

```

As I say the animation fires correctly the 1st time but not on subsequent times. I'm just trying this by changing the public "open" property in the inspector

thanks

# Answer
> 1 votes
As per usual I worked out what was going wrong just after I answered the question! I had one of my old boolean conditions still attached to the transition from closing to an idle state. This never got evaluated so my close animation state was continuously running, although it wasn't on a loop. I just needed to change this to an exit time. This still seems a bit clunky to me so if anyone can provide a better approach I would be interested in hearing it

---
Tags: unity, unityscript
---