# Question
Title: How to loop section from a song correctly?
I'm programming a little Music Engine for my game in C# and XNA, and one aspect from it is the possibility to loop a section from a song. For example, my song has an intropart, and when the song reached the end ( or any other specific point ), it jumps back where the intropart is just over. ( A - B - B - B ... )

Now I'm using IrrKlank, which is working perfectly, without any gaps, but I have a problem:

The point where to jump back is a bit inaccurate. Here's some example code:

```
public bool Passed(float time)
    {
        if ( PlayPosition >= time )
            return true;
        return false;
    }
//somewhere else
if( song.Passed( 10.0f ) )
   song.JumpTo( 5.0f );

```

Now the problem is, the song passes the 10 seconds, but play a few milliseconds until 10.1f or so, and then jumps to 5 seconds. It's not that dramatic, but very incorrect for my needs. I tried to fix it like that:

```
public bool Passed( float time )
{
      if( PlayPosition + 3 * dt >= time && PlayPosition <= time )
             return true;
      return false;
}

```

( dt is the delta time, the elapsed time since the last frame )

But I don't think, that's a good solution for that.

I hope, you can understand my problem ( and my english, yay /o/ ) and help me :)

# Answer
> 3 votes
In my opinion, a simpler and more usual solution is having two different tracks: an intro and a loop section. Then, the only problem is detecting when the intro ends (quite easy, albeit not perfectly precise if using 30fps). Then the second track can be played with looping enabled.

Thus, you reduce the errors in the reproduction to a slight delay when starting the loop for the first time, instead of everytime the loop section has to be rewinded.

# Answer
> 0 votes
The ideal solution would be to know beforehand which parts of the song need to be loaded next into the buffer. Each 'section' A - B - C would have a start and end time, and it would be your lower level streaming system that would load the correct parts of the file in the correct order. You would have to have a fixed bitrate for this to work though, and it could be quite difficult finding where in the file you need to skip to next.

I had a quick look at the irrKlang site and they boast about the possibility to write your own file format readers/decoders to extend the engine with it, so you may want to give that a shot.

There is also a tutorial here to override the file access - you could give my original idea a shot, or you could mix it up with multiple sounds like Elideb said. You could extend your CMyReadFile class to have access to multiple files (like PartA.wav, PartB.wav, PartC.wav), and you could override the read method, so rather than just :

```
return (s32)fread(buffer, 1, sizeToRead, File);

```

You could do something like :

```
switch(CurrentSectionToPlay)
{
case A:
    return (s32)fread(buffer, 1, sizeToRead, FileA);
case B:
    return (s32)fread(buffer, 1, sizeToRead, FileB);
}

```

Which means the song would seamlessly change section without having to synchro Plays & Stops.

---
Tags: xna, music
---


# Question
Title: How can I set the rotation of a shape to the same as my image?
The way you set rotations of images is different from setting shape rotations. So how can I make the shape have the same rotation as my image?

This is how my image rotates:

```
if(input.isKeyDown(Input.KEY_RIGHT))
        {
            rotate += rotateSpeed * delta;
            image.rotate(rotate - image.getRotation());
        }

```

How can I get the same effect but with a shape?

For example:

How can I get that rectangle to be at the same rotation as the car?

# Answer
> 4 votes
If you're using Slick2D to create the rectangle. Slick2D has a Shape class that can be used to describe such things (rectangles, circles, etc.).

I imagine you're using a shape like this for collision because it has methods like `intersect()`(link) that allow you to detect such things.

`Shape` also has a nice method called `transform()`(link). It can be used to apply a transform to your shape. Transforms are essentially matrix operations. Luckily you don't need to know too much about the matrix operation because it's easy to create transforms. `Transform` has a static method called `createRotateTransform`. You can use this to specify a rotation to create a transform to apply to the shape.

So the short of it would be, use something like this:

```
rotatedCarShape = carShape.transform(Transform.createRotateTransform(radiansToRotate)));

```

Remember that `transform` does not alter the original shape, so you don't have to worry about the rotations adding up, but you do need to remember to draw the correct transformed shape.

---
Tags: opengl, java, lwjgl, slick
---


# Question
Title: Algorithm to simplify building/structural meshes
I am looking for an algorithm to simplify the meshes of buildings or similar structures.

EDIT: I had made a comment that Hoppe's algorithm tends to make meshes more and more spherical with simplification. But, I am not sure about it, so am deleting the comment. Buildings in contrast should tend to become more and more rectangular with increasing simplification. The D3DX extensions for D3D in version 9.0 (d3dx9.lib) used to have classes to do progressive mesh simplification. See:
http://doc.51windows.net/Directx9\_SDK/?url=/directx9\_sdk/graphics/reference/d3dx/functions/mesh/d3dxgeneratepmesh.htm
http://msdn.microsoft.com/en-us/library/windows/desktop/bb281243(v=vs.85).aspx

# Answer
The best results I've seen for this when a mesh is decimated. Decimating the mesh attempts to reduce the polygon count with minimal shape changes. The decimated meshes retain their shapes fairly well and this would be ideal for non-organic structures like buildings. Though it even works on organic structures as you can see here:

There are a few different techniques at work here. Such as estimating an average plane, performing "half-edge collapses" and more. There are numerous publications available that discuss implementing a decimation process. For further reading:

http://webdocs.cs.ualberta.ca/~anup/Courses/604\_3DTV/Presentation\_files/Polygon\_Simplification/7.pdf

http://www.cs.uu.nl/docs/vakken/ddm/slides/papers/schroeder.pdf

http://www.cg.tuwien.ac.at/courses/Seminar/SS2002/Knapp\_paper.pdf

http://www.jerrytalton.net/research/Talton04SSMSA.report/Talton04SSMSA.pdf
> 17 votes

---
Tags: 3d-meshes
---


# Question
Title: How do I prevent a KActor from changing the orientation of its Z-Axis?
So I have an object that inherits from KActor that I would like to behave as a dynamic physics object, but I want its Z-Axis to remain upright, but very stiffly. I've tried the bStayUpright that triggers the "Stay Upright Spring". The problem is, it's a spring, and the object in question oscillates into position when I want it to remain oriented properly without wobbling.

In the image above, the yellow block has fallen onto the gray box, and it is currently pivoting about the contact point as it tries to right itself.

Should I be tweaking the `StayUprightMaxTorque` and `StayUprightTorqueFactor` parameters, or should I be using a Constraint of some sort?

# Answer
> 1 votes
So we decided we wanted the wall not to rotate at all, and here is the solution:

```
local QuadForceKCreateBlock MeshActor;
local RB_ConstraintActor AConstraint;

MeshActor = spawn(class'QuadForceKCreateBlock', none, 'PowerCreate_Block', BlockLocation(), m_PreparedRotation, , false);

AConstraint = Spawn(class'RB_ConstraintActorSpawnable', MeshActor, '', MeshActor.Location, rot(0,0,0));
AConstraint.ConstraintSetup.bSwingLimited = true;
AConstraint.ConstraintSetup.bTwistLimited = true;
AConstraint.ConstraintSetup.LinearYSetup.bLimited = 0;
AConstraint.ConstraintSetup.LinearYSetup.bLimited = 0;
AConstraint.ConstraintSetup.LinearZSetup.bLimited = 0;
AConstraint.InitConstraint(MeshActor, None);

```

The ConstraintSetup defaults to having TwistLimit and SwingLimit = 0, which will allow no rotation. It also defaults to TwistLimitSoft and SwingLimitSoft false, which guarantees you don't get any motion at all.

---
Tags: physics, udk
---


# Question
Title: What is the cost of custom made 2D game sprites?
> **Possible Duplicate:**
> How much to pay for artwork in an indie game?

I am looking for sprites similar in style to those of Final fantasy Tactics, but with a much higher resolution that will work well for both a browser and an iPhone.

In terms of animations:

* Walking in 4 directions
* Swinging with 1 hand
* Some sort of "casting animation" (depending on cost I may use the 1 hand swing with a wand).
* Taking a hit
* Kneeling
* Fallen

**How much would something like that cost per sprite?**

# Answer
> 1 votes
Placing a price is almost impossible because it more or less depends on what sort of deal you work out with whoever you commission to create the art for you.

---
Tags: 2d, sprites, costs
---


title: Direct2D gamma correction

text:
# Question
Title: Direct2D gamma correction
I'm using direct2d and direct3d together and having an issue with gamma correction. My direct3d backbuffer is using an SRGB format and when I render images from direct2d onto the direct3d surface, they appear washed out. I can't seem to figure out how to enable SRGB on the direct2d end. Does anyone know who to do this?

# Answer
> 1 votes
I'm not very familiar with Direct2D, so I don't know if images there can be marked as being in sRGB format; but a possible workaround is to maintain two render target views of your back buffer, one in sRGB format and the other in regular (linear) RGB. When rendering Direct2D stuff where you just want to copy the pixels straight over, you'd use the linear one; when rendering 3D stuff you'd use the sRGB one. Note that this doesn't mean having two separate buffers, just two render target views of the same buffer. There could be a performance cost switching between them, though, so if possible you'd want to ensure you only switched once per frame.

---
Tags: directx11, sharpdx
---


# Question
Title: Box2d too much for Circle/Circle collision detection?
I'm using cocos2d to program a game and am using box2d for collision detection. Everything in my game is a circle and for some reason I'm having a problem with some times things are not being detected as a collision when they should be.

I'm thinking of rolling up my own collision detection since I don't think it would be too hard.

Questions are:

1. Would this approach work for collision detection between circles?
a. get radius of circle A and circle B.
b. get distance of the center of circle A and circle B c. if the distance is greater than or equal to the sum of circle A radius and circle B radius then we have a hit
2. Should box2d be used for such simple collision detection? There are no physics in this game.

# Answer
What you've suggested will work if you only care about collision *detection*, **but** there is a difference between collision detection and collision *response*.

For the latter, Box2D provides contact friction, and realistic (mass-based) transfer of linear inertia, and most importantly, transfer of angular/rotational inertia. These all lend to the look and feel that you may already be used to, in which case I'd advise keeping Box2d.

If you seriously need only very simple collision response mechanics that just pushes the two bodies some distance away from each other, and your game's motion is mostly kinematic (think platformers) rather than simulated physics (think racing games), then yeah, you're all good to rip out Box2d.

EDIT: Also, you may want to look at a solid Box2D example before you abandon it. Circle collisions work just fine, and you may have a discrepancy between actual body size, and rendered size. Box2D bodies will sometimes interpenetrate, but that only happens when they're being pressed together very tightly with no space to push away from each other.
> 7 votes

# Answer
1. Your approach for collision detection will work as you're checking collisions only between circles, you can use **Pythagoras** to get the distance between the points. The method you described is often used and it's called **circle to circle collision detection**.
2. If you are not going to use anything else provided by box2d, I don't think you need it.
> 0 votes

# Answer
What you are describing is Pythagorean theorem and is very suitable to this task (however square roots can 'slow').

```
//in c++
bool sphereIntersection(object *A,  object *B)
{
    float dist;
    float factorX = A->position.x - B->position.x;
    float factorY = A->position.y - B->position.y;
    dist = sqrtf(factorX*factorX + factorY*factorY);

    if (dist < (A->radius + B->radius)/2)
        return true;
    return false;
}

```

Although box2d supports intersection only tests, with no response, through the `isSensor` parameter, this makes the whole library overkill. The advantage that you would get from using box2d is other algorithms that it uses (eg. sweep and prune).

If you have a lot of objects you could write your own broadphase to make the intersection tests faster
> 0 votes

---
Tags: collision-detection
---


# Question
Title: Rotating a cube using jBullet collisions
How would one go about rotating/flipping a cube with the physics of jBullet?

Here is my Draw method for my cube object:

```
    public void  Draw() {
    // center point posX, posY, posZ
    float radius = .25f;//size / 2;

    glPushMatrix();
    glBegin(GL_QUADS);
        //top
        {
            glColor3f(5.0f,1.0f,5.0f); // white
            glVertex3f(posX + radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY + radius, posZ + radius);
        }

        //bottom
        {
            glColor3f(1.0f,1.0f,0.0f); // ?? color
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
        }

        //right side
        {
            glColor3f(1.0f,0.0f,1.0f); // ?? color
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }

        //left side
        {
            glColor3f(0.0f,1.0f,1.0f); // ?? color
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
        }

        //front side
        {
            glColor3f(0.0f,0.0f,1.0f); // blue
            glVertex3f(posX + radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY + radius, posZ + radius);
            glVertex3f(posX - radius, posY - radius, posZ + radius);
            glVertex3f(posX + radius, posY - radius, posZ + radius);
        }

        //back side
        {
            glColor3f(0.0f,1.0f,0.0f); // green
            glVertex3f(posX + radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY - radius, posZ - radius);
            glVertex3f(posX - radius, posY + radius, posZ - radius);
            glVertex3f(posX + radius, posY + radius, posZ - radius);
        }
    glEnd();
    glPopMatrix();

}

```

This is my update method for the cube position:

```
    public void Update() {
    Transform trans = new Transform();
    cubeRigidBody.getMotionState().getWorldTransform(trans);

    posX = trans.origin.x;
    posY = trans.origin.y;
    posZ = trans.origin.z;

    Quat4f outRot = new Quat4f();
    trans.getRotation(outRot);
    rotX = outRot.x;
    rotY = outRot.y;
    rotZ = outRot.z;
    rotW = outRot.w;
}

```

I am assuming I need to use glrotatef, but it does not seem to work at all when I try that..

this is how I have tried to rotate the cubes:

```
    GL11.glRotatef(rotW, rotX, 0.0f, 0.0f);
    GL11.glRotatef(rotW, 0.0f, rotY, 0.0f);
    GL11.glRotatef(rotW, 0.0f, 0.0f, rotZ);

```

Here is how I am getting the XYZ for the cubes from jBullet:

```
    public void Update() {
    //cubeTransform = new Transform();
    cubeRigidBody.getMotionState().getWorldTransform(cubeTransform);

    posX = cubeTransform.origin.x;
    posY = cubeTransform.origin.y;
    posZ = cubeTransform.origin.z;

    processTransformMatrix(cubeTransform);
}

```

# Answer
You are mixing quaternions with euler angles. You would need to do a conversion to make it work. Instead of rotations around specific axis, I recommend to use the transformation matrix from Bullet physics directly. This includes the position as well.

```
// These can be pre-allocated.
float[] matrix = new float[16];
Transform transform = new Transform();
FloatBuffer transformationBuffer = BufferUtils.createFloatBuffer(16);

// Get the transformation matrix from JBullet.
MotionState motionState = rigidBody.getMotionState();
motionState.getWorldTransform(transform);
transform.getOpenGLMatrix(matrix);

// Put the transformation matrix into a FloatBuffer.
transformBuffer.clear();
transformBuffer.put(transformation);
transformBuffer.flip();

GL11.glPushMatrix(); // Save the current OpenGL transformation
GL11.glMultMatrix(transformationBuffer); // Apply the object transformation
renderObject();
GL11.glPopMatrix(); // Restore the saved transformation

```
> 2 votes

---
Tags: java, physics, rotation, lwjgl, bullet-physics
---


# Question
Title: Scaling sprite velocity / co-ordinates in Android
I'm trying to find the answer to a question that I've had for a long time, but am having trouble finding it! I hope someone can help :-)

I'm trying to find information on how to scale sprite velocity / movement / co-ordinates.

What I mean by this is how do I get a sprite to move at the same speed relative to the screen size / DPI so that it takes the same amount of real-time to get from one side of the screen to the other?

All of the posts pertaining to sprite scaling that I can find on the various forums relate to the size of the sprite, but this part of it I'm OK with so far, it's just that when I move a sprite, it kind of gets there at different speed depending on the dpi / resolution of the device. I hope I'm making sense.

This is the code I have so far, instead of using explicit amounts, like 1, I'm using something like the following:

```
platSpeedFloat= (1 * (dpi/160)); //Use '1' so on an MDPI screen, the sprite will move by 1 physical pixel

```

Then basically what I'm doing is something like this: (all varialble previously declared)

```
platSpeedSave+=platSpeedFloat; //Add the platSpeedFloat value to the current platSpeedSave value

platSpeed=(int) platSpeedSave; //Cast to int so it can be checked in the following statement

if (platSpeed==platSpeedSave) //Check the casted int value to float value stored previoiusly

{floorY=floorY-platSpeed; //If they match then change the Y value

platSpeedSave=0;} //Reset

```

Would be grateful if someone could assists - hope I'm making sense. The above doesn't seems to work the sprite moves 'faster' on lower DPI screens.

Thanks

# Answer
You want to move the ball from side to side of the screen in the same amount of time. You can convert the screen resolution to \[0.0, 1.0\] (sometimes called screen coordinates to world coordinates conversion). Then you calculate the speed using that,

E.g: with one coordinates, you should expand it to use X and Y. You want the ball move from left to right on 10 second so:

```
vel = 1.0 / 10
pos = pos + vel * dt
pos_in_screen = pos * SCREEN_SIZE

```

And work with that.

Other thing to have in mind, your shorter screen size should be \[0.0, 1.0\] but the other dimension will be \[0.0, 1.X\] depending on the screen ratio.

**UPDATE:**

dt: delta time in seconds, time between frames. E.g: with 30fps, dt=1/30

Example with X coords. If your sprite start in pos 0 (left side of the screen), with a screen with 10x10 pixels, the update should be:

```
vel = 1.0 / 10 (it could remains the same between frames)
pos = pos + vel * dt = 0 + (1.0/10) * (1.0/30) = 1/300
pos_in_screen = pos * SCREEN_SIZE = 1/300 * 10 = 1/30

```

With a screen of 100x100 you only change the last sentence:

```
pos_in_screen = pos * SCREEN_SIZE = 1/300 * 100 = 1/3

```
> 1 votes

---
Tags: android, sprites, movement, screen, pixel
---


title: Is a Single Texture Cube Map Possible?

text:
# Question
Title: Is a Single Texture Cube Map Possible?
I'm currently developing a test project to explore OpenGL 3 texturing abilities. I have a simple cube, made of 8 vertices and 36 indices. I want each of the cubes faces to have a different texture, so I devised this texture:

I made it obvious which sections I want visible (I hope...). In Direct3D, I once made a skybox, and I used a cubemap. However, I had to split it into 6 different textures. This is annoying and hard to manage, it would be nice to have just one texture. Is this even possible? I read somewhere that I could do this by duplicating vertices, is that a good idea? Someone else said I could do it in the shader, but that also baffles me...

# Answer
> 6 votes
If you want to do it with a single texture, the easiest thing to do is UV map your sky cube model to that texture layout. Then, you can use a normal texturing shader.

# Answer
> 3 votes
If you want to get a cube map texture starting with that image on disk, then just extend your texture loader to slice up that image into individual cube map faces!

# Answer
> 1 votes
It is possible to stack the cube faces vertically in a single image, and either split the original bitmap in software, or offset the pointer to the image data when uploading the textures to the GPU. (usually by: `bytesPerPixel * width * (height \ 6) * faceIndex`).

A custom cube mapping shader is not difficult, selecting the largest component of the view ray as z, calculate texture coordinates using this formula: `ray.xy/ray.z * 0.5 + 0.5`. To select an image, divide v by 6, and add 1/6 * the face's index. Filtering across the edges might be more of a challenge.

---
Tags: opengl, textures, cubemap
---


# Question
Title: Procedural Planets, Heightmaps and Textures
I am currently working on an OpenGL procedural planet generator. I hope to use it for a space RPG, that will not allow players to go down to the surface of a planet so I have ignored anything ROAM related. At the moment I am drawing a cube with VBOs and mapping onto a sphere.

I am familiar with most fractal heightmap generating techniques and have already implemented my own version of midpoint displacement (not that useful in this case I know).

My question is, what is the best way to procedurally generate the heightmap. I have looked at libnoise which allows me to make tilable heightmaps/textures, but as far as I can see I would need to generate a net like this.

Leaving the tiling obvious.

Could anyone advise me on the best route to take?

Any input would be much appreciated.

# Answer
> 17 votes
First of all, I'm not sure why you want to implement a height map (i.e. geometry displacement) if people won't be able to land, it just seems more efficient to normal map it or something.

With that said, what you want is to convert from an arbitrary `(x, y, z)` to a `(u, v)` coordinate, which is trivial. No cubemap needed.

1. Every `(u, v)` texel has a height (heightmap `RGB = height`) and a position `(x, y, z) = pos`.
2. Find and normalize the position, `NORMAL(x, y, z) = N`.
3. New vertex = `pos+N*height`.

This will work better with a higher tessellation. Also use the proper `libnoise` spherical mapping for your heightmap, which will look something like this (but black and white):

# Answer
> 2 votes
I have never tried this myself, but it looks like a very interesting way to generate spherical landscapes. http://freespace.virgin.net/hugo.elias/models/m\_landsp.htm

# Answer
> 1 votes
Midpoint displacement height mapping is a good place to start. OP, why do you think it isn't?

OP is good to model the planet surface as a cubemap, because any flat map (e.g. mercator projection) is going to have distortions that are ugly and complicated, mathwise.

If I were OP, I would forget the large scale planet geometry at first. I would make a cubemap where each face is 2\**N+1 pixels (2,3,5,9,17,33...) and each texel encodes a height \[0..N) where 0 is the altitude of the expected lowest trench and N is the altitude of the expected highest mountain on the planet.

I would then calculate random heights for the eight vertices of the cube, and propagate them into the six squares of the cube map, so that each vertex shows up three times.

As I recursively generate fractal heights for the midpoints of the edges, I would make sure to propagate face edge vertices to the other face that shares them.

Once I'm done, I have a cube map where all the edge texels are doubled and all the corner texels are tripled. No need to convert it to a normal map - I'd use the algorithm in Morten Mikkelsen's paper to render normals directly from the heightmap at runtime.

At runtime I would probably render a quad that covers the projection of the planet to the screen, and do a single ray-sphere intersection test in the pixel shader to find whether I hit the planet and where. Sure beats rasterizing a highly-tessellated sphere model, and gets a nice smooth edge too.

# Answer
> 1 votes
Midpoint displacement noise, with the maximum displacement scaled by the absolute longitude of the pixel can produce a spherical noise map quickly. Color tables taking altitude, slope, and sunlight or longitude as paramaters can be used to shade the planet automatically.

---
Tags: opengl, textures, procedural-generation, cubemap
---


# Question
Title: How can you store item data from a game?
> **Possible Duplicate:**
> Would it be better to use XML/JSON/Text or a database to store game content?
> How to choose how to store data?

When I look at games such as warcraft 3, or Diablo, or basically any games that contain items in them I notice that each item is unique. They all have different stats, different graphics, different names.

I took a wild guess that they don't use XML, although I know I might be wrong, but I just figured they use something that isn't easily human-editable to prevent casual hacking.

How is data such as item attributes stored in a game (2d or 3d, I suppose it works the same way in both)?

# Answer
Good guess, XML is not by default the simplest method of storing plain text data. It depends on a lot of things, mostly what *existing* tools you are planning to use. Some questions to ask yourself before choosing XML:

* Do you feel XML editors make you (or your team) more productive? (If you are a programmer, used to a text editor, the answer is probably no.)
* Do you want schema validation? (Will your data structure be complex enough to require this.)
* What will XML bring to the table another, less verbose, easier text-editable, plain text configuration language doesn't have?

As Jonathan Blow eloquently put it:

> Many modern programmers seem to have some kind of knee-jerk inclination to use XML whenever a textual format is desired, but I think XML is one of the worst file formats ever created, and I have no idea why anyone uses it for anything at all, except that perhaps they drank the XML Kool-Aid or have XML Stockholm Syndrome. Yes, there are XML-specific tools out there in the world, and whatever, but I didn’t see how any such tool would be of practical use to us. One of our primary concerns is human-readability, so that people can make intelligent decisions when attempting to resolve revision control conflicts. XML is not particularly readable, but we can modify our own format to be as readable as it needs to be in response to whatever real-world problems arise.

Some alternatives are:
> 6 votes

# Answer
It really depends on the engine or tools used internally by the developer. The simplest method of storing data is, in fact, XML, or XML-like syntax. The format for models will probably be something different; for example, Unity uses the FBX format for it's models (and it can also import MAs and MBs, Maya's format). The format for textures would be any standard image format.

It's true that XML would be easily hacked, since it's human readable, and that's why the files will be compressed and possibly encrypted in the installation, both to prevent hand-editing and also to cut down on the space the game requires. The engine will have a way of reading the compressed files.

Going off on a tangent, it's entirely possible that the data will not be compressed. A specific example I can provide is that some early installs of GTA IV had an uncompressed/unencrypted WeaponsInfo file, which I had a lot of fun editing :)

EDIT: Here is a link to the WeaponInfo file from GTA IV. Note that it is XML: https://dl.dropbox.com/u/2789977/WeaponInfo.xml
> 3 votes

---
Tags: xml, file-format, asset-management, configuration
---


# Question
Title: How to make my simple round sprite look right in XNA
Ok, I'm very new to graphics programming (but not new to coding). I'm trying to load a simple image in XNA which I can do fine. It is a simple round circle which I made in photoshop. The problem is the edges show up rough when I draw it on the screen even with the exact size. The anti-aliasing is missing. I'm sure I'm missing something very simple:

```
        GraphicsDevice.Clear(Color.Black);

        // TODO: Add your drawing code here
        spriteBatch.Begin();
        spriteBatch.Draw(circle, new Rectangle(10, 10, 10, 10), Color.White);
        spriteBatch.End();

```

Couldn't post picture because I'm a first time poster. But my smooth png circle has rough edges. So I found that if I added:

spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.NonPremultiplied);

I can get a smooth image when the image is the same size as the original png. But if I want to scale that image up or down then the rough edges return. How do I get XNA to smoothly resize my simple round image to a smaller size without getting the rough edges?

# Answer
> 2 votes
Have a read of this article on texture aliasing (and the ones it links). It explains exactly why you are having this issue.

While there are many techniques for rendering an anti-aliased circle, the simplest one for your situation is to turn on mipmaps for your texture.

To do so, make sure your texture is in an XNA Content Project. Select it and press F4. You should see the following window:

Expand the "Content Processor" node and set "Generate Mipmaps" to true. You don't need to make any changes to your code to make mipmaps work.

(Note that "Premultiuply Alpha" is set to true by default. You should leave this set and use `BlendState.Alpha`, which is the default for `SpriteBatch.Begin`. Leave texture filtering as the default of "linear" as well.)

---
Tags: xna, antialiasing
---


title: Rotating multiple points at once in 2D

text:
# Question
Title: Rotating multiple points at once in 2D
I currently have an editor that creates shapes out of (X, Y) coordinates and then triangulate that to make up a shape of those points.

What will I have to do to rotate all of those points simultaneously? Say I click the screen in my editor, it locates the point where I've clicked and if I move the mouse up or down from that point it calculates rotation on X and Y axis depending on new position relevant to first position, say I move up 10 on the Y axis it rotates that way and the same way for X. Or simply, somehow to enter rotation degree: 90, 180, 270, 360, for example.

I use VertexPositionColor at the moment.

What are the best algorithms or methods that I can look at to rotate multiple points in 2D at once?

**Also:**

Since this is an editor I do now want to rotate it on the Matrix, so if I want to rotate the whole shape 180 degree that's the new "position" of all the points, so that's the new rotation = 0 for example. Later on I probably will use World Matrix rotation for this, but not now.

# Answer
You need to define a center for rotation... in this case the box center..

then when you detect the mouse down you store vector (A) from the center to the mouse coords... this is your initial vector.... ans should store your shape rotation as initial rotation.

then while you move the mouse and it continues being down you calculate the second vector (B) from the center to the current mouse coords...

now you can calculate the angle between to vectors... as you should know it can be calculated normalizing the two vectors and calcultaing the dot product... so you get the cosine... now you get the angle with an arccosine function...

this angle should be added to the initial rotation of your shape... ans set the new rotation for your shape.

so you only have to build your transform matrix for your shape...

the easiest way is to store your vertex coords relative to the center of the shape, if you don't store that way you should get that points relative to it...

Your transform matrix should similar to this...

```
// Supposing your coords are absolute
Matrix transform = Matrix.CreateTranslation( -Center )
                 * Matrix.CreateRotationZ(rotation)
                 * Matrix.CreateTranslation (Center );

// Supposing your coords are relative, center is (0,0)
Matrix transform = Matrix.CreateRotationZ(rotation)

```

You should realize that usually the right way is the easy way... you should use matrix transforms... I'd do something similar to this:

```
  class Bone2D {
      Vector2 Translation;
      float Rotation;
      float Scale;
      Bone Parent;
      Matrix Local { get { return Matrix.CreateScale(scale)
                                * Matrix.CreateRotationZ(rotation)
                                * Matrix.CreateTranslation(translation); } }
      Matrix Absolute { get{ return (Parent == null)
                                       ?  Local
                                       : Parent.Absolute * Local; }}
  }

  class Shape : Bone2D {

      Vector2[] RelativeCoords;  // Relative to your shape center
      Vector2[] AbsoluteCoords {
           get{
             return RelativeCoords.Select(r => Vector2.Transform(r, Absolute)
                                  .ToArray();
           } }
  }

```

This way the shape you show in your example, would have two bones...

1) the parent bone that translates the shape,

2) the shape that is a bone itself and can be rotated easily... or scaled or translated again relative to the parent bone of course... ;)

This editor is quite old... I have a new version... but the video shows what you can achieve doing it right... http://www.youtube.com/watch?feature=player\_detailpage&v=K9R5v5Va4CI#t=28s

I hope this to be useful... ;)
> 2 votes

# Answer
Generic and math-heavy answer ahead.

We have the following points:

Origin *O* = (*x*O, *y*O), the origin (or centre) of the object and the origin point for our rotation.

Starting point *S* = (*x*S, *y*S), the point at which the mouse was pressed down and/or the mouse was when the rotation was initiated.

Current (mouse) point *M* = (*x*M, *y*M), the point the mouse is at right now during the rotational operation.

Your rotation can then be expressed as 2x2 matrix calculated from the unit vectors pointing from the origin to the starting point and to the current mouse point respectively.

*D*S = (*x*DS, *y*DS) = (S - O) / ||S - O||

*D*M = (*x*DM, *y*DM) = (M - O) / ||M - O||

> **Warning**
>
> We can calculate the inverse of the second matrix so easily because we know that the matrix is made out of an unit vector - and thus the determinant has the value of exactly **1**. This is *not* a generic formula for calculating such.

The resulting matrix can again be expressed as a unit vector of direction, in case you ever need it:

*D*R = (*x*DM *x*DS \+ *y*DM *y*DS, - *x*DM *y*DS \+ *y*DM *x*DS)

The rotation matrix describes a rotation about the origin (0, 0) - not about *your* origin. For this, the points first have to be moved so that the object origin is the same as world origin, rotated, then moved back to their original position. In other words:

*P*rotated = *R* x (*P*original \- *O*) + *O*

You can express the translations as 3x3 matrices if you first extend your 2D vectors by an anonymous dimension with the constant value of 1 for all of them; the three transformations can then be pre-calculated into one single matrix by simple matrix multiplication.
> 1 votes

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


title: Detecting End of Animation

text:
# Question
Title: Detecting End of Animation
So I am making a death animation for a game. enemy1 is a UIImageView, and what I'm doing is when an integer is less than or equal to zero, it calls this deathAnimation which only happens once. What I want to do is use a CGPointMake right when the animation is finished being called. Note that before the deathAnimation is called, there is another animation that is constantly being called 30 times a second. I'm not using anything like cocos2d.

```
if (enemy1health <= 0) {
    [self slime1DeathAnimation];
    //How can i detect the end of this animation
}

```

This is how the animation is done:

```
-(void)slime1DeathAnimation{
    enemy1.animationImages = [[NSArray alloc] initWithObjects:
                              [UIImage imageNamed:@"Slime Death 1.png"],
                              [UIImage imageNamed:@"Slime Death 2.png"],
                              [UIImage imageNamed:@"Slime Death 3.png"],
                              [UIImage imageNamed:@"Slime Death 4.png"],
                              [UIImage imageNamed:@"Slime Death 5.png"],
                              nil];
    enemy1.animationDuration = 0.5;
    enemy1.animationRepeatCount = 1;
    [enemy1 startAnimating];
}

```

If you need more code just ask

# Answer
> 2 votes
If you are animating the views using CoreAnimation, then you can set a method as callback that will be invoked after the animation is over using the following method:

```
[+ (void)setAnimationDidStopSelector:(SEL)selector][1]

```

More details on how the animation is done could help to answer your question right.

# Answer
> 0 votes
In your case the best way to go would be to set the `animationDuration` and `animationRepeatCount` property of the `UIImageView` and then schedule a timer to call a selector method just after calling `startAnimating` with the same delay as the duration of animation.

```
enemy1.animationDuration = 0.5;
enemy1.animationRepeatCount = 1;
[enemy1 startAnimating];
[NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(somemethod) userInfo:nil repeats:NO];

```

Also you can stop the animation for the enemy1 object in that `somemethod`.

# Answer
> 0 votes
Use +animateWithDuration:animations:completion: (available on iOS 4+), you will have a completion block. Something like :

```
[UIVIew animateWithDuration:0.5
                 animations:^{
    enemy1.animationImages = [[NSArray alloc] initWithObjects:
                              [UIImage imageNamed:@"Slime Death 1.png"],
                              [UIImage imageNamed:@"Slime Death 2.png"],
                              [UIImage imageNamed:@"Slime Death 3.png"],
                              [UIImage imageNamed:@"Slime Death 4.png"],
                              [UIImage imageNamed:@"Slime Death 5.png"],
                              nil];
}
                  completion: ^(BOOL finished){
   // Your animation is finished
}];

```

Hope this help.

---
Tags: iphone, animation, objective-c
---


title: How do I switch from XNA to C++?

text:
# Question
Title: How do I switch from XNA to C++?
So, I heard somewhere that Microsoft intends to phase out XNA in favour of using the DirectX method. I've always wanted to learn, but all I ever did in XNA was simple 2D games. I was wondering if there's any good tutorials out there for people migrating from XNA...thanks in advanced!

# Answer
> 2 votes
Unless you feel constrained by XNA 4.0 capabilities there is no really reason to switch from it to DirectX. At least you can try MonoGame which is actually recommended by MS employee (that can be a fake account of course, but I see no reasons to doubt it). The migration to MonoGame is pretty straightforward.

If you are making simple games there is no really need for pure DirectX. You also can be overwhelmed by technical details required for it.

# Answer
> 1 votes
I found this tutorial that perhaps is going to be useful for you. Is about starting Managed DirectX applications and 2D, (you'll finde code there also). Hoping it helps.

http://www.codeproject.com/Articles/3470/Managed-DirectX-Tutorial-Part-1-The-Title-Screen http://www.codeproject.com/Articles/3601/Managed-DirectX-Tutorial-Part-2-Samus-Running

# Answer
> 0 votes
Although this site is extremely ugly the tutorials are really in helpful and easy to follow. Rastertek

---
Tags: xna, c++, directx
---


title: Shortcut for NodeJS server

text:
# Question
Title: Shortcut for NodeJS server
I am tired of typing "cd c:\socket\nodejs" "node testserver.js"

Into the command promt..

How do I create a shortcut or bat for it?

# Answer
> 0 votes
To do exactly as you asked, create a `.bat` file and inside type:

```
cd c:\socket\nodejs
node testserver.js

```

But what I would suggest is installing this thing I came across the other day called Lineman. It makes use of Grunt to automatically check for file updates on the fly. It also has built in support for Test'Em which makes unit testing a breeze. Using all of this, you could write a batch script more like this:

```
cd c:\socket\nodejs
lineman run

```

then just go from there without even needing to run `node` periodically. Furthermore, you could create a second batch like so:

```
cd c:\socket\nodejs
lineman spec

```

and keep that open so you can check in and make sure all of your unit tests are always passing.

---
Tags: software-engineering, node.js
---


title: OpenGL: Light at end of tunnel effect

text:
# Question
Title: OpenGL: Light at end of tunnel effect
Anyone knows any implementation of the "light at the end of tunnel" effect? where the outside is entirely bright and gradually becomes more visible?

The reverse could also be true, where the inside of the tunnel is very dark until you step in and gradually start seeing

Any implementation/algo will help or even the actual name of the effect

Thanks

# Answer
> 7 votes
Two ways, basically.

One's HDR. You adjust brightness of the image according to the brightness of the image (if that makes sense). It's somewhat hard to control and might not work exactly the way you want. The implementation is somewhat hard to do, too.

The other one's a simple sprite that gets brighter when the camera is further away and looking from the right direction. A very simple approach: additive rendering, one simple equation to control brightness, sprite must fit in the scene (where all sprites are sorted according to distance from camera).

You can find the performance of both techniques in different "parts" of Half-Life 2. The first can be found in "Lost Coast" while the second can be found in the original game, Half-Life 2 (the highway levels, to be specific), here's a video that displays this technique.

---
Tags: opengl, lighting
---


# Question
Title: How to make 2D water like in this video?
I wanna make water and waves for my little 2D PC game like in this video: http://www.youtube.com/watch?v=ooU6cTeirlQ I don't know how to write a similar shader. Does anybody know how to write a similar shader? Or is it possible to do the waves without shaders?

# Answer
> 1 votes
It's hard to tell how this is made *exactly* (except by the developer), but let me summarize what has already been said in comments, with some additions:

* This is a 3D mesh seen from the edge, probably a simple grid
* Each vertex of the grid is following spring physics affected by:

1. A sine wave
    2. The dolphin diving in and out
    3. Their depth
* Backface culling is disabled, and different textures/shading are used on both faces (tips)
* The textures might be animated (animated UVs?), but this isn't really visible
* There's some kind of alpha blending involved on the last row(s) of vertices

Additionally, to perfect the illusion, you have some animated sprites for the dolphin splashes, and a trail that seems to be a textured quad strip.

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


title: State changes in entities or components

text:
# Question
Title: State changes in entities or components
I'm having some trouble figuring how to deal with state management in my entities.

I don't have trouble with Game state management, like pause and menus, since these are not handled as an entity component system; just with state in entities/components.

Drawing from Orcs Must Die as an example, I have my MainCharacter and Trap entities which only have their components like PositionComponent, RenderComponent, PhysicsComponent.

On each update the Entity will call update on its components. I also have a generic EventManager with listeners for different event types.

Now I need to be able to place the traps: first select the trap and trap position then place the trap.

When placing a trap it should appear in front of the MainCharacter, rendered in a different way and following it around. When placed it should just respond to collisions and be rendered in the normal way.

How is this usually handled in component based systems?

(This example is specific but can help figure out the general way to deal with entities states.)

# Answer
One interesting application of a component system is that you can change an entity's components at *runtime* if you designed it to be able to handle such. The state of an entity thus becomes the sum of both which components are assigned to it and which values those hold.

For your example, you can first create the trap with a `BuildControllerComponent` (governing the reaction to player controls in build phase), a `PositionComponent` and a `RenderComponent`. The last one has one data field which governs the pixel shader(s) used, and one of them gives the trap-to-be-build a "ghostly" look. You'll notice there are *no* physics components assigned yet.

Upon placing the trap, the components get exchanged. The `BuildControllerComponent` isn't needed anymore, so it gets removed. The `RenderComponent`'s shaders get replaced with your normal standard view of the trap. Finally, `PhysicsComponent` as well as whatever else is needed for the trap to work are added to the entity.

In an inheritance-based approach, this is equivalent to having a constructor for an `ActiveTrapEntity` class which takes a `BuildTimeTrapEntity` class as its arguments, the second one being used to render the trap during building it, the first one being used for the trap after it's in place.
> 6 votes

# Answer
I don't like the idea of entities calling updates on their components (systems should be doing the work), and that's going to lead to issues with keeping components unaware of each other.

You can add an additional component called "State". It will be accessed by your render and collision systems. The state component is just a flag that has multiple states available to it. For the situation you describe the states would be `Play` and `Build`. When the render system sees that the state is `Build` it will draw the object translucent. When the collision system sees the `Build` state, it will not process collisions with the player.

But really, if you don't have systems and you're relying on components to do all the work you're going to run into a lot of issues. Components shouldn't know about each other and they shouldn't be doing processing.
> 5 votes

---
Tags: component-based, state
---


title: CUDA 4.1 Update

text:
# Question
Title: CUDA 4.1 Update
I'm currently working on porting a particle system to update on the GPU via the use of CUDA. With CUDA, I've already passed over the required data I need to the GPU and allocated and copied the date via the host. When I build the project, it all runs fine, but when I run it, the project says I need to allocate my h\_position pointer. This pointer is my host pointer and is meant to hold the data.

I know I need to pass in the current particle position to the required cudaMemcpy call and they are currently stored in a list with a for loop being created and interated for each particle calling the following line of code:

`m_particleList[i].positionY = m_particleList[i].positionY - (m_particleList[i].velocity * frameTime * 0.001f);`

My current host side cuda code looks like this:

```
float* h_position; // Your host pointer. This holds the data (I assume it's already filled with the data.)
    float* d_position; // Your device pointer, we will allocate and fill this
    float* d_velocity;
    float* d_time;
    int threads_per_block = 128; // You should play with this value
    int blocks = m_maxParticles/threads_per_block + ( (m_maxParticles%threads_per_block)?1:0 );
    const int N = 10;
    size_t size = N * sizeof(float);
    cudaMalloc( (void**)&d_position, m_maxParticles * sizeof(float) );
    cudaMemcpy( d_position, h_position, m_maxParticles * sizeof(float), cudaMemcpyHostToDevice);

```

Both of which were / can be found inside my UpdateParticle() method. I had originally thought it would be a simple case of changing the h\_position variable in the cudaMemcpy to m\_particleList\[i\] but then I get the following error:

> no suitable conversion function from "ParticleSystemClass::ParticleType" to "const void \*" exists

I've probably messed up somewhere, but could someone please help fix the issues I'm facing. Everything else seems to running fine, it's just when I try to run the program that certain things hit the fan.

# Answer
I don't see any place in your code where you assign anything to h\_position, so naturally the CudaMemcpy call fails.

your m\_particleList seems to contain ParticleType objects which hold at least position and velocity attributes, not just a single float.

Additionally, do your particles have x,y,z positions and velocities? You can't just pass the pointer to m\_particleList into the CudaMemcpy function then, your list of n ParticleTypes will not fit in an array of n floats.

You might need to create something along the lines of

```
struct particle{
    float x,y,z,vx,vy,vz;
};

```

in both host and device code, and use `particle*` instead of `float*`.
> 1 votes

# Answer
As melak47 has pointed out, the first problem is that you first need to allocate memory for h\_position:

```
h_position = malloc(sizeof(float) * m_maxParticles);
memset(h_position, 0, sizeof(float) * m_maxParticles);

```

But it also seems like you're trying to copy back your integrated positions into your particles array on the host? I really don't recommend copying large amounts of data from the GPU to the CPU every frame. Only do it if you *absolutely must*. You haven't mentioned what, if anything, you need to computer on the CPU, but I would say you can just push the particles to the GPU once and let it handle things from there. To do that, you can declare your particle struct:

```
struct Particle {
    float x, y, z;
    float vx, vy, vz;

    __device__ __host__ Particle() {
        x = 0; y = 0; z = 0;
        vx = 0; vy = 0; vz = 0;
    }
};

```

Prefixing the default constructor with `__device__` and `__host__` indicates that the `Particle` struct can exist on both the CPU and GPU. Now, you can allocate space for your particles on the CPU, and fill out the information:

```
Particle* particles = malloc(m_maxParticles * sizeof(Particle));
// Fill out positions and initial velocities as you'd like.

```

And then copy the data over to the GPU:

```
Particle* d_particles;
cudaMalloc( (void**)d_particles, m_maxParticles * sizeof(Particle) );
cudaMemcpy( d_particles, particles, m_maxParticles * sizeof(Particle), cudaMemcpyHostToDevice );

```

As I said before, you should probably only do this copy once, unless you are adding or removing particles on a frame-by-frame basis.
> 0 votes

---
Tags: gpu, cuda
---


# Question
Title: If I draw a rectangle, then extrude it, will it be identical to a box?
If I draw a rectangle, then extrude it, will it be identical to a box? I mean, will bottom face be closed as in box?

# Answer
It will not be identical to the Box primitive, as the result will be a Rectangle with an Extrude modifier.

It may have the same apparent geometry like a box, assuming that you toggle the flag to cap the beginning and end of the extrude.

The origin of the resulting object will be at the base, which may differ from where the origin of a box normally is.
> 5 votes

---
Tags: 3dsmax
---


# Question
Title: Error in my Separating Axis Theorem collision code
**EDIT 2: Made some more alterations, now the one area i'm still confused on is: how to work out the vector to project on the separation axes? My projectOnto(..) method has some huge gaps now and i know i need to use the dot product but i don't really understand how to. I left my old code in there commented out so you can see what i was trying to do following an article on SAT but i don't really understand how it works. Appreciate any help!**

**EDIT:** Made several alterations thanks to suggestions below but the problem is still the very same.

The only collision experience i've had was with simple rectangles, i wanted to find something that would allow me to define polygonal areas for collision and have been trying to make sense of SAT using these two links

Though i'm a bit iffy with the math for the most part i feel like i understand the theory! Except my implementation somewhere down the line must be off as:

(excuse the hideous font)

As mentioned above i have defined a CollisionPolygon class where most of my theory is implemented and then have a helper class called Vect which was meant to be for Vectors but has also been used to contain a vertex given that both just have two float values.

I've tried stepping through the function and inspecting the values to solve things but given so many axes and vectors and new math to work out as i go i'm struggling to find the erroneous calculation(s) and would really appreciate any help. Apologies if this is not suitable as a question!

**CollisionPolygon.java:**

```
package biz.hireholly.gameplay;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import biz.hireholly.gameplay.Types.Vect;

public class CollisionPolygon {

    Paint paint;

    private Vect[] vertices;
    private Vect[] separationAxes;
    int x; //actually the positions of the object that owns this CollisionPolygon
    int y;

    CollisionPolygon(Vect[] vertices){

        this.vertices = vertices;
        //compute edges and separations axes
        separationAxes = new Vect[vertices.length];
        for (int i = 0; i < vertices.length; i++) {
            // get the current vertex
            Vect p1 = vertices[i];
            // get the next vertex
            Vect p2 = vertices[i + 1 == vertices.length ? 0 : i + 1];
            // subtract the two to get the edge vector
            Vect edge = p1.subtract(p2);
            // get either perpendicular vector (my perp method returns (y, -x)
            // then get a nomralized version
            Vect normal = edge.perp().normalize();
            separationAxes[i] = normal;
        }

        paint = new Paint();
        paint.setColor(Color.RED);

    }

    public void draw(Canvas c){
        if(x != 0 && y != 0){
            for (int i = 0; i < vertices.length; i++) {
                Vect v1 = vertices[i];
                Vect v2 = vertices[i + 1 == vertices.length ? 0 : i + 1];
                c.drawLine(
                        x + v1.x,
                        y + v1.y,
                        x + v2.x,
                        y + v2.y,
                        paint);
            }
        }
    }
    public void update(int xPos, int yPos){
        x = xPos;
        y = yPos;
    }

    /* consider changing to a static function */
    public boolean intersects(CollisionPolygon p){

        // loop over this polygons separation exes
        for (Vect axis : separationAxes) {
              // project both shapes onto the axis
            Vect proj1 = this.projectOnto(axis);
            Vect proj2 = p.projectOnto(axis);
              // do the projections overlap?
            if (!proj1.overlap(proj2)) {
                // then we can guarantee that the shapes do not overlap
                return false;
            }
        }

        // loop over the other polygons separation axes
        Vect[] sepAxesOther = p.getSeparationAxes();
        for (Vect axis : sepAxesOther) {
              // project both shapes onto the axis
            Vect proj1 = this.projectOnto(axis);
            Vect proj2 = p.projectOnto(axis);
              // do the projections overlap?
            if (!proj1.overlap(proj2)) {
                // then we can guarantee that the shapes do not overlap
                return false;
            }
        }
        // if we get here then we know that every axis had overlap on it
        // so we can guarantee an intersection
        return true;
    }

    private Vect projectOnto(Vect axis) {
        //When using the dot function we take into account the absolute position using the owning objects x & y
        //   Not entirely certain if neccessary? appears to make no difference for the moment at least..

        //TODO: need some sort of loop to figure out a vector that represents the max breadth of the polygon onto the current separation axes
        Vect breadth =...

        //This is the simplified formula for projecting a vector onto a normalised vector (the axis)
        return  axis.multiplyByScalar(breadth.dot(axis));

        /*
         * OLD FUNCTIONLITY
        float min = axis.dot(new Vect(vertices[0].x+x, vertices[0].y+y));
        float max = min;
        for (int i = 1; i < vertices.length; i++) {
            float p = axis.dot(new Vect(vertices[i].x+x, vertices[i].y+y));
            if (p < min) {
                min = p;
            }
            else if (p > max) {
                max = p;
            }
        }
        Vect minMaxProj = new Vect(min, max);
        return minMaxProj;*/

    }

    public Vect[] getSeparationAxes() {
        return separationAxes;
    }

    public Vect[] getVertices() {
        return vertices;
    }

}

```

**Vect.java:**

```
    package biz.hireholly.gameplay.Types;

/* NOTE: Can also be used to hold vertices! Projections, coordinates ect */

public class Vect{
    public float x;
    public float y;

    public Vect(float x, float y){
        this.x = x;
        this.y = y;
    }

    public Vect perp() {
        return new Vect(y, -x);
    }

    public Vect subtract(Vect other) {
        return new Vect(x - other.x, y - other.y);
    }

    public boolean overlap(Vect other) {
        if(y > other.x && other.y > x){
            return true;
        }
        return false;
    }
    /* used specifically for my SAT implementation which i'm figuring out as i go,
     * references for later..
     * http://www.gamedev.net/page/resources/_/technical/game-programming/2d-rotated-rectangle-collision-r2604
     * http://www.codezealot.org/archives/55
     */
    /* doing away with..
    public float scalarDotProjection(Vect other) {
        //multiplier = dot product / length^2
        float multiplier = dot(other) / (x*x + y*y);
        //to get the x/y of the projection vector multiply by x/y of axis
        float projX = multiplier * x;
        float projY = multiplier * y;
        //we want to return the dot product of the projection, it's meaningless but useful in our SAT case
        return dot(new Vect(projX,projY));

    }*/
    public float dot(Vect other){
        return (other.x*x + other.y*y);
    }
    public float length(){
        return (float)Math.sqrt((x*x + y*y));
    }
    public Vect normalize(){
        return new Vect( x / length(), y / length());
    }
    public Vect multiplyByScalar(float s){
        return new Vect(x*s, y*s);
    }
}

```

# Answer
> 2 votes
Your draw method takes two parameters xPos & yPos. is this the position of the object? If so then you also need to add xPos & yPos to your vertices when projecting on to an axis. If 'pos' is the position of the shape then you project as follows;

```
float p = axis.dot(new Vect(vertices[i].x+xPos, vertices[i].y+yPos);

```

instead of

```
float p = axis.dot(vertices[i]);

```

You need to project the absolute position of the vertex rather than the relative (to the centre) position of the vertex.

# Answer
> 1 votes
It looks like your overlap method isn't correct. I think it should be;

```
if(!(y<other.x || other.y < x))
    return true;

```

or equivalently;

```
if(y > other.x && other.y > x)
    return true;

```

# Answer
> 1 votes
So there are a couple of problems I see right away. The first is that you are not actually normalizing the "normals" of your `CollisionPolygon`'s faces. The second is that when you do your vector projections you want the projected vector, and not it's dot product with the vector you're projecting. So you might want to have a projection function that looks like this:

```
public Vect projectOnto(Vect other) {
    float denominator = other.dot(other);
    // Might want to check for denominator == 0
    return other.scale((this.dot(other) / denominator);

```

You can use that to project the half-vectors of your polygons onto the separating axes.

The next problem I see is your `overlap` function in the `Vect` class. I'm not exactly sure what it's supposed to be checking; perhaps you can clarify? I interpret it to check if two vectors, being treated as lines, intersect. While it seems like those comparisons may be accurate, it will not actually acurately determine a line intersection, nor will it be useful for the Separating Axis Theorem.

The idea of SAT is that an axis separates two polygons if half the sum of the projected polygons onto that axis is greater than the length of the projection of the vector between them. I've found Metanet Software to provide the best explanation of SAT, for various shapes.

So, I think if you modify your intersection code to be doing length checks rather than line intersection checks, and also fix the normalization of your separating axes, your code should work. There may still be a few tweaks to make after that. The combination of bugs is what makes this difficult to debug.

Hope this helps :)

# Answer
> 1 votes
I'd like to propose a different method. Although I could see the dot-method working, it seems to require tracking a lot of data relative to each edge. I would argue that it might be simpler (this is really debatable) to use cross products. I'll downplay the difficulty in creating a new vector3 class...but on the plus side it really only needs a static `cross()` function, and possibly a few constructors:

When applied to flat (z = 0) 3-vectors, the cross product can tell you which side of a line contains a point by using the right-hand rule. In your case, if the point is on the right-hand side of every edge, then it must be inside the shape. So: **if the cross product of every edge of the polygon with a new vector3 based on the colliding vertex all have a positive sign, then you have a collision.** Psuedo-code for a collision detector function which examines polygons A and B:

```
bool isCollision = true

for(i = 1; i < A.vertices.count; i++) {
  foreach (Vect bVert in B.verticies) {
    // loop around the end of A.vertices ,
    // like you've already done in your code

    // as in your code, the edge vector
    edge = A.vertex[i] - A.vertex[i - 1]

    // 3-vector along the edge
    edge3 = new Vector3(edge.x, edge.y, 0)

    // 3-vector from leading point of edge to potential colliding vertex
    vertvect = bVert - A.vertex[i]
    vertvect3 = new Vector3(vertvec.x, vertvec.y, 0)

    // get output 3-vector...
    pointCross = Vector3::cross(edge3, vertvect3)
    // ...and check to see if it points up or down
    if (pointCross.z < 0) {  // it is on the left
       // ergo the point is outside your shape
       isCollision = false
       // exit this double loop as early as possible
       break foreach;
    }
  }
  if (!isCollision){
    break for;
  }
}

return isCollision

```

When it comes time to implement a cross prodcut, that wikipedia page links to the involved math. :)

# Answer
> 1 votes
Here is the separation code I wrote for a project a while ago (it's in c++, but the logic is the important thing). The Separated method takes a normal vector (it doesn't have to be normalized for the SAT to work), and all the world coordinates for the two objects. This code is written for triangles, hence the loops to 3. But should world for any convex polygon. Hope it helps.

static bool CheckForCollisionSAT(Triangle\* t1,Triangle\* t2){ SATcount++; sf::Vector2f verts1\[3\]; sf::Vector2f verts2\[3\]; t1-\>GetVerts(verts1); t2-\>GetVerts(verts2);

```
    sf::Vector2f normals1[3];
    sf::Vector2f normals2[3];
    t1->GetNormals(normals1);
    t2->GetNormals(normals2);

    for(int i=0;i<3;i++){
        bool sep;
        sep=Separated(normals1[i],verts1,verts2);
        if (sep) return false;//no collision
        sep=Separated(normals2[i],verts1,verts2);
        if (sep) return false;//no collision
    }

    return true;

}

bool static Separated(sf::Vector2f normal,sf::Vector2f verts1[],sf::Vector2f verts2[]){
    float min1=FLT_MAX;
    float min2=FLT_MAX;
    float max1=-FLT_MAX;
    float max2=-FLT_MAX;
    for(int i=0;i<3;i++){//project t2 on to 1's normals
            float d=Vector::dot(normal,verts2[i]);
            if(d>max2) max2=d;
            if(d<min2) min2=d;
        }
        for(int i=0;i<3;i++){//project t1 on to 1's normals
            float d=Vector::dot(normal,verts1[i]);
            if(d>max1) max1=d;
            if(d<min1) min1=d;
        }

    if(max1<min2 || max2 <min1) //check for overlap
        return true;

    return false; //no separation on this normal
}

```

---
Tags: java, collision-detection, separating-axis-theorem
---


title: Setting density for Android game

text:
# Question
Title: Setting density for Android game
I am developing an Android game, in which a ball (bitmap) translates( is in motion). So I have provided motion equations for the ball. I have checked my app on Samsung galaxy S2 whose actual density is roundly 252 dpi, and It works fine on that. So my question is that Does these motions of bitmaps in surfaceView, depends on actual density of phone( i.e 252 dpi for S2) or generalized density(i.e 240 dpi).

I am confused whether if I run this app on 235 dpi smartphone, So will it have the same performance of motion as it is on Galaxy S2( with 252 dpi) or it would be little slow ?

Any help will be appreciated.

Let me elaborate it with coding. For example a linear motion of a ball is defined as with this equation x=x+4; Now If I run this app, on Samsung galaxy S2(252dpi, and hdpi), So It will give me a particular speed motion, let say P is the speed of the ball. Now If I run this application on Samsung Galaxy S3(300+ dpi, xhdpi), So the ball speed gonna be slow on this density, meaning less than the speed P.

So I will need the same speed on xhdpi density phone. So will use these conversion formulas ; dx= (x\*160)/240; px= (dx\*320)/160; Hence the speed will be either exact or little different from P.(This is my confusion). That Whether the speed will be as same as it was on S2.

So my Question at this point is that my app worked on Samsung Galaxy S2 with the speed p, that I desired. As S2 is of 252 dpi, So Should I Include 240(Generalized density or 252 (Actual density) in my this line of coding ? dx= (x\*160)/240;

Thanks !

# Answer
> 1 votes
You can call the getDensity method on your Canvas. This will tell you what Android is doing. To test performance, I would try your app on a couple different phones. I'm in a Android development Meetup group, and we help each other out by testing apps on difference devices. If this isn't possible, you could setup different AVD targets with differing densities. While this won't show you the performance, it will tell you what Android is doing with densities. There is a good article on the Android developer site that talks about supporting multiple screen sizes & densities: http://developer.android.com/guide/practices/screens\_support.html

---
Tags: android, resolution, screen
---


# Question
Title: Multiple textures on a mesh created in blender and imported in xna
I created a cube in blender which has multiple images applied to its faces. I am trying to import the model into xna and get the same results as shown when rendering the model in blender. I go through every mesh (for the cube its only one) and through every part but only the first image used in blender is displayed in every face. The code I am using to fetch the texture looks like that:

```
foreach (ModelMesh m in model.Meshes)
{
   foreach (Effect e in m.Effects)
   {
      foreach (var part in m.MeshParts)
      {
         e.CurrentTechnique = e.Techniques["Lambert"];
         e.Parameters["view"].SetValue(camera.viewMatrix);
         e.Parameters["projection"].SetValue(camera.projectionMatrix);
         e.Parameters["colorMap"].SetValue(modelTextures[part.GetHashCode()]);

      }
   }
   m.Draw();
}

```

Am I missing something?

---

EDIT:

Here is the code for getting the texture from the blender and use it in the XNA:

```
foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    BasicEffect basicEffect = part.Effect as BasicEffect;

                    if (basicEffect != null)
                        modelTextures[part.GetHashCode()] = basicEffect.Texture;

                    part.Effect = material.effect;

                }
            }

```

# Answer
This is an exact duplicate of a question on StackOverflow.com, but since the question has to be on gamedev.stackexchange.com to flag it as a duplicate I'll give you the link here with some added info as an answer.

The answer: Drawing a textured cube with multiple sides in XNA 4.0

The difficulty here is that you can't easily tell XNA in one draw call to use multiple diffuse textures for the model. Lets give you a bit more background. Each model consists of vertices (points in 3D space with some additional information). Multiple vertices are used to construct triangles and from these triangles your cube is made. Often each vertex contains a tuple (u,v) which tells the GPU what pixel of the texture should be mapped to that vertex. For each triangle the 3 UVs from the vertices is then linearly interpreted over the surface of the triangle so that we can paint the triangle in the correct colours.

Now as you can see there is no information here on which texture to use. This entire scheme was designed to use one texture. Now vertices can contain arbitrary information so we could think of scheme were we create our own vertex type, say `VertexPositionNormalUVTextureID` instead of the common/default `VertexPositionNormalTexture` we'd then have to write a shader to which we stream 6 textures and the cube, having replaced its vertices by our own type. This would work perfectly but its quite a bit of work. So the other approach is to just see the cube as 6 planes and render each plane normally, setting a different texture each time. This saves us from a lot of hassle, like converting vertices and writing our own (extremely one-case-use) shader.
> 1 votes

---
Tags: xna, textures, blender
---


# Question
Title: Characteristics, what's the inverse of (x*(x+1))/2?
In my game you can spend points to upgrade characteristics. Each characteristic has a formula like:

A) **out = in** : for one point spent, one pont gained (you spend 1 point on Force so your force goes from 5 to 6)

B) **out = last level** (starting at 1) : so the first point spent earns you 1 point, the next point spent earns you an additional 2 and so on (+3,+4,+5...)

C) **The inverse of B)** : You need to spend 1 point to earn one, then you need to spend 2 to earn another one and so on.

I have already found the formula for calculating the actual level of B when points spent = x :

charac = (x\*(x+1))/2

But I'd like to know what the "reverse" version of B) (usable for C) is, ie. if I have spent x points, how many have I earned if 1 spent gives 1, 1+2=3 gives 2, 1+2+3=6 gives 3 and so on.

**I know I can just calculate the numbers** but I'd like to have the formula because its neater and so that I can stick it in an excel sheet for example...

**Thanks!**

ps. I think I have nailed it down to something like charac = sqrt( x\*m +k) but then I'm stuck doing number guessing for k and m and I feel I might be wrong anyway as I get close but never hits the spot.

# Answer
You should probably ask it on Math.SE ...

---

Short version: Your formula is generally known as "sum of integers", a special case of a power sum and generally written as follows:

Calculating the inverse requires solving the quadratic equation 0.5*x*2 \+ 0.5*x* \- *charac* = 0 for *x*.

In the basic formula for solving such (see the link for explanation), we can set

*a* = 0.5

*b* = 0.5

*c* = -*charac*

.. and calculate that the results are ...

x = (-0.5 ± √(0.52 \+ 4 x 0.5 x *charac*)) / 2 x 0.5 = -0.5 ± √(2 x *charac* \+ 0.25)

Since one of the results is always negative it can't be true, so this leaves us with the following formula, which is positive for all positive real-valued *charac*:

x = √(2 x *charac* \+ 0.25) - 0.5

In most cases you'll probably want to round the result down to the nearest integer.
> 4 votes

---
Tags: game-design, mathematics
---


# Question
Title: Video playback in games - formats & decoding
What free / non-restrictive open-source solutions (not GPL) are available for decoding game videos?

The requirements are simple:

* a relatively easy to use C API
* encoded files must be quite small
* there must be an application that converts videos from any format (whatever codec is installed on Windows or equivalent amount of internally decoded formats)
* decoding has to happen fairly quickly
* bonus points go to file formats that are popular / actively supported and developed

# Answer
> 5 votes
**FFmpeg** lets you decode all kinds of audio and video data thanks to libavcodec. Most of it is licensed under the LGPL, which allows commercial use, but some parts are under GPL, and some parts might infringe patents.

You might be able to avoid legal problems by using the free **Ogg format** (maintained by the Xiph.org foundation), probably with Vorbis+Theora for lossy compression. FFmpeg offers support for decoding those through libvorbis and libtheora, and will let you convert from any other format through the `ffmpeg` command-line tool.

---
Tags: video
---


# Question
Title: forward rendering and multiple shadow maps
I have two light sources on my scene. I created two fbo's which store depth textures for these lights. A render loop looks like this:

```
bind fbo1
save depth values for first light
unbind fbo1

bind fbo2
save depth values for second light
unbind fbo2

enable additive blending

bind first depth texture
render scene
bind second depth texture
render scene

disable additive blending

```

For one light source the program works fine. For many light sources I use an additive blending to acumulate lighting results but then some objects become transparent (for example when an object which is further away from the camera is drawn before an object which is closer to the camera). How to resolve that problem ? How should I accumulate lighting effects for many light sources (many shadow maps) ? P.S. I use OpenGL/GLSL 3.3+

# Answer
Ensure depth testing is enabled when you perform your additive blending passes. This will prevent pixels from being blended into the framebuffer if they are behind another object. You will have to initialize the depth buffer first, of course. This can be done with a depth-only pass at the start of the frame (enable depth testing and writing, but disable color writes). The depth pass can also be combined with the first lighting pass; just render opaque rather than using additive blending for that first pass.
> 3 votes

---
Tags: opengl, lighting, shadows
---


title: Send less Server Data with "AFK"

text:
# Question
Title: Send less Server Data with "AFK"
I am working on a 2D (Realtime) MultiPlayer Game.

With Construct2 and a Socket.IO JavaScript Server.

Right now the code does not include the Array for each Player.

```
var io = require("socket.io").listen(80);
var x = 10;
io.sockets.on("connection", function (socket)
{
socket.on("message", function(data)
{
x = x+1;
});
});
setInterval(function()
{
io.sockets.emit("message", 'Pos,' + x);
},100);

```

I noticed a very annoying problem with my server today. It sends my X Coordinates every 100 milliseconds.

The Problem was, that when I went into another Browser Tab, the Browser stopped the Game from running. And when I went back, I think the Game had to run through all the packages. Because my Offline Debugging Button still worked immediately and the Online Button only responded after some seconds.

So then I changed my Code so that it would only send out an update when it received a player Input:

```
var io = require("socket.io").listen(80);

var x = 10;

io.sockets.on("connection", function (socket) {
socket.on("message", function(data)
{

x = x+1;
io.sockets.emit("message", 'Pos,' + x);
});
});

```

And it Updated Immediately, even when I had been inactive on the Browser Tab for a long time. Confirming my suspicion that it had to get through all the data. **Confirm Please!**

It would be insane to only send information on Client Input in a Real Time Game.

But how would I write a AFK function?

I would think it is easier to run a AFK Boolean Loop on the Server.

**Here is what I need help for:**

```
playerArray[Me]
if (   "Not Given any Input for X amount of Seconds"    )
{
 "Don't send Data"
}
else
{
 "Send Data"
}

```

# Answer
You could check for the `blur` event in the `window`, when that happen you send a message to the server saying "this player is afk", the server won't send messages to afk players, when your player comes back you send another message saying "not afk anymore" and start sending messages again.

It should be something like this:

```
window.onblur = function() {
    server.send(PLAYER_AFK, connection);
}

window.onfocus = function() {
    server.send(PLAYER_NOT_AFK, connection);
}

```

onblur is called whenever an object loses focus, in this case when the user changes the tab (or the browser stop being active.) onfocus is called when the window receives the focus again.
> 5 votes

---
Tags: javascript, client-server
---


# Question
Title: Need efficient way to keep enemy from getting hit multiple times by same source
My game's a simple 2D one, but this probably applies to many types of scenarios.

Suppose my player has a sword, or a gun that shoots a projectile that can pass through and hit multiple enemies.

While the sword is swinging, there is a duration where I am checking for the sword making contact with any enemy on every frame. But once an enemy is hit by that sword, I don't want him to continue getting hit over and over as the sword follows through. (I do want the sword to continue checking whether it is hitting other enemies.)

I've thought of a couple different approaches (below), but they don't seem like good ones to me. I'm looking for a way that doesn't force cross-referencing (I don't want the enemy to have to send a message back to the sword/projectile). And I'd like to avoid generating/resetting multiple array lists with every attack.

* Each time the sword swings it generates a unique id (maybe by just incrementing a global static long). Every enemy keeps a list of id's of swipes or projectiles that have already hit them, so the enemy knows not to get hurt by something multiple times. Downside is that every enemy may have a big list to compare to. So projectiles and sword swipes would have to broadcast their end-of-life to all enemies and cause a search and remove on every enemy's array list. Seems kind of slow.
* Each sword swipe or projectile keeps its own list of enemies that it has already hit so it knows not to apply damage. Downsides: Have to generate a new list (probably pull from a pool and clear one) every time a sword is swung or a projectile shot. Also, this breaks down modularity, because now the sword has to send a message to the enemy, and the enemy has to send a message back to the sword. Seems to me that two-way streets like this are a great way to create very difficult-to-find bugs.

# Answer
The resolution for this could be the same you'd use for processing held keys on the keyboard.

```
colliding = checkCollision(this, otherObject);
if(colliding && !previousFrameColliding) {
    //trigger hit with otherObject
} else if(colliding && previousFrameColliding) {
    //still in contact, do what you will here, or nothing
} else if(!colliding && previousFrameColliding) {
    //we just finished a collision
} else {
    //not colliding
}
previousFrameColliding = colliding;

```

If you're likely to only be colliding with one object at a time, this will work. If you're going to be colliding with multiple objects at the same time, you'll need to track the "currently colliding with" objects and check against that.
> 8 votes

# Answer
With something like a sword swing, you don't actually care that much about the question "who am I colliding with right now?" What you care about is not state, but rather, *change of state*, that is, you're interested in knowing when the sword/enemy collision state changes from `false` to `true`. The only way you can measure changes in state is to compare your current state against your previous state.

So have each object maintain two sets: the set of what I'm colliding with *now* (i.e., this frame), and the set of what I was colliding with *previously* (i.e., last frame). The difference of these two sets provides you with the set of *things I am colliding with now that I was not previously colliding with*.

I see no reason why this would necessarily involve passing messages back and forth between the colliding entities. Your sword knows that it hit something; it doesn't need to get approval from the thing it hit! Make the sword tell the enemy that it was hit, and have the enemy react appropriately, or whatever makes sense in your scenario.
> 4 votes

# Answer
You don't necessarily need a huge list. For example, if you were limited to just four players, you could just use four small timers on each enemy (one for each possible player). These timers could be as small as a few bits, where all timers are decremented every 1/5th of a second or so.

If you have a larger number of players, you can again only worry about a small number of hits at a time. Even if you have 1,000 players, it's unlikely that all 1,000 will be attacking the same enemy. The enemy can keep a small fixed-size ring buffer of recent attackers and timestamps. If by some chance too many players do attack a particular enemy, you can just ignore the attacks that would "overflow" the buffer (it's unlikely to be a big deal to the players).

Yet another option is to keep a single global set of attack-to-enemy timers. If you have a small number of actively engaged enemies at any given time, this approach can keep your memory usage way down, have an extremely minimal impact on performance (might even be better due to keeping things in cache better; profile to be sure, of course), and is pretty simple to implement. This is how many of the Minecraft-like games keep track of transitory per-block state (like mining "damage," for example), since storing state in blocks is not feasible for memory reasons and since there's generally only a tiny handful of blocks in a transitory state at any given point in time despite there being something like 2x10^17 blocks.

For larger highly-multiplayer worlds, you could use the shared attack-to-enemy timer set, but instead of making it global store it per-zone (or chunk or area or whatever processing-oriented spatial subdivision you use).

Remember that with games, you don't need to be 100% correct. You only need to be correct enough to keep players happy. You don't actually *need* to allow an enemy to take damage from all attacks but only once; you only need to ensure that the combat feels fun and enjoyable. If you run into an algorithmic problem, in games you often just change the game play slightly to eliminate the problem entirely or rescope it to an easier to solve problem, rather than trying to actually solve something which quite possibly has no acceptable solutions.
> 2 votes

# Answer
One variable on the sword:

When you swing the sword you clear it.

When it hits something you store the ID of the object that it hit.

When you find that it's colliding with the last object that it hit you disregard the hit.
> 0 votes

---
Tags: collision-resolution, efficiency
---


# Question
Title: How to determine which thrusters to turn on to rotate the ship?
The configuration of the ship changes dynamically, so I have to determine which thruster to turn on when I want to rotate the ship clockwise or counter clockwise. The thrusters are always axis aligned with the ship (never at an angle) and are either on or off. Here's one of the possible setups:

What I've tried so far is to visualize the firing vector and the direction vector to the center of mass of the ship:

Unfortunately, I didn't get very far with that.

# Answer
Success! Here it is, and it's rotating as it should:

What I've done is the following: for each thruster, I calculate the magnitude of the torque, in relation to the center of mass.

```
private function thrustTorque():Float
{
    // distToCom is the distance vector between the thruster and center of mass
    // fire angle is a unit vector representing the direction of the thruster
    var distAngle = Math.atan2(distToCOM.y, distToCOM.x);
    var fireAngle = Math.atan2(dir.y, dir.x);
    var theta = fireAngle - distAngle;
    var torque = distToCOM.length * Math.sin(theta);
    return torque;
}

```

The equation for the mangitude of torque, according to wikipedia, is `T = rF sin(theta)`, where :

* r is the distance between the thruster and COM
* F is the magnitude of the force applied (I leave that out, pretending it's just one, because I only care about the sign).
* theta is the angle between the two vectors

When the player presses left, I check the sign of torque for that thruster - if it's less than zero, I fire the thruster. It's just the opposite for turning clockwise.

This could probably be improved by using the dot product to calculate the cosine of the angle between the vectors, but that'll have to wait until tomorrow.

Finally, here's a live demo.
> 22 votes

# Answer
The general 3D expression for torque is the cross product of displacement and force: **T** = **r****F**. In two dimensions, a scalar value for the torque will suffice, and given only four orthogonal orientations for the thrusters, we can write in piecewise form:

* Force in direction +x: T = F * (-ry)
* Force in direction -x: T = F * (ry)
* Force in direction +y: T = F * (rx)
* Force in direction -y: T = F * (-rx)

Here, F is the magnitude of the force generated by the thrusters, rx and ry are x- and y-components of the vector from pivot point to thruster. Positive torques tend to rotate the ship counter-clockwise. Using the four formulae above, it is trivial to deduce the sign of the torque each thruster produces.

For a modestly accurate representation of physics, you need not only know the sign of the thrust, but also its total magnitude and the rotational inertia. Moreover, you might not simply want to activate all properly aligned thrusters to do a rotation.

As drawn, full power to thrusters B, D and E will maximize the rotation, but will also accelerate the ship to the right. Shutting down D will prevent this. If instead, accelerating right is intended, but a clockwise rotation is not, the most efficient way to go is enabling both C and F at two thirds of full power along with D.

If this isn't beyond the scope of what you're trying to do, you would have to write some sort of solver for the equations of motion, clearly not a simple task.
> 14 votes

# Answer
A few different things. First, we need to recognize that this is an under-constrained problem. That is, there are many different combinations of thrusters which can fire to result in rotation in the same direction. I'm assuming that in your situation there are only two states for the thrusters, "on", and "off", and all thrusters output equal force.

Second, eyeballing your model, it looks like your "center of mass" is not actually your center of mass. Luckily, this won't effect your calculations for the torque. However, it will effect your calculations for the center of mass displacement. I'm not sure if you care about accuracy on that level though, since your "center of mass" is at least the closest square to the true center of mass.

Third, if you want to calculate how a certain thruster will affect the rotation, you have it right, although you are using an inefficient formula. Torque can be calculated as `r x F`, which has magnitude `r*F*sin(theta)`. However, calculating the angles in this case is an inefficient method. Instead, you should use the cross-product definition of torque directly, as this will be much simpler using the representations you have. Because all your vectors have no z component, the formula for cross product simplifies greatly.

Without changing the results of your computation at all, we can just update your code

```
private function thrustTorque():Float
{
    var torque = distToCOM.x*dir.y-distToCOM.y*dir.x;
    return torque;
}

```

That's much nicer (and faster).

You suggest in your own answer that your solution is to fire all the thrusters with torque in the right direction. Now, that pretty much solves the question that you asked. However, I expect that some point along the line, you're going to find that your strategy is not so satisfactory, if a user holds down the "rotate" button, and all thrusters with a positive torque rotate, potentially moving them on top of rotating them (I'm not sure of the level of detail of your simulation, if you actually do calculate the forces from the thrusters, or if you just visually show them firing and then rotate your model with a constant acceleration or something. Either way, you want the thrusters to be firing at least approximately accurately).

You make no consideration of the net force on the ship. If you had arbitrary thruster amounts, then this could turn into a pretty complicated problem. However, since our thrusters have only two states, it's pretty simple to analyze. I'm not sure exactly what our goal is here, so I could imagine two different ones: first, we want to minimize the total force, while still keeping the torque in the direction we want. Second, we want to maximize the ratio of torque to total force.

As an aside, if you could imagine an additional "thruster volume" control that affects the power of *all* thrusters simultaneously, then you could set this control so that your two solutions have equal torque, and you see that the second solution can only have a *smaller* displacement than the first. However, we need to remember that if it is possible to fire the thrusters so that you only rotate and do not move at all, then both solutions will be the same.

So, we're going to go with the second solution, based on the arguments of the previous paragraph. Now, when analyzing the total force, we can simply note that there are only four directions the engines can point. Thus the total force in the x direction is just the number of thrusters pointing left minus the number pointing right, and likewise for the y direction.

After writing up this far, I have to think some more about the algorithm to optimize it. I think the rest of my post is helpful as is, so I'm posting it, but I'll update when I figure out the best way to optimize this configuration (I've thought of a few ways to get approximate answers, but none of them are exact).
> 7 votes

---
Tags: mathematics, physics
---


# Question
Title: Copies of GameScene created when called additional times
**UPDATE:** It no longer crashes after removing `[self removeAllChildrenWithCleanup:YES];` from `onExit`. The artifacts still remain though.

**UPDATE 2:** Found my problems. See my answer below.

I have a game with a level select managed by a `SceneManager`, which basically just uses `ReplaceScene`. The first time I load a level everything works fine. On subsequent calls, for example: completing the level and continuing to the next, things blow up. The level loads fine, but when I try to pan the map or try to move the player the game crashes. Debugging through I found that there are multiple occurrences of `self` and related children like `player` and `mapLayer`.

As a test, I put this code in my `ccTouchesBegan`:

```
NSLog(@"test %i", [self retainCount]);

```

The first time a level is loaded, it gives:

```
test 2

```

The second time I load a level it gives:

```
test 2
test 1

```

as in it spits out both values by looping through twice, not just appending an output to the last. It continues with this pattern for each subsequent load. So the third time will give `2 1 1`.

Particular code that causes the game to crash involve calling `_tileMap.tileSize` because there is a second `GameScene` with a tileMap that was supposedly destroyed, so it has tileSize and mapSize of 0.

I noticed dealloc doesn't really ever get called, so I tried to manage some things with `-(void) onExit`

```
-(void) onExit
{
    [self unscheduleAllSelectors];
    [_player stopAllActions]; //stop any animations just in case. normally handled in ccTouchesEnded
    [self removeAllChildrenWithCleanup:YES];
}

```

I never replace the GameScene while I'm in a GameScene; if the level is completed it goes to a GameOver scene, or I use a back button that goes to the LevelSelect scene.

This is \[the relevant parts of\] my `init`, in case something like the adding of children matters:

```
-(id) init
{
    _mapLayer = [CCLayer node];

    //load data for level
    GameData *gameData = [GameDataParser loadData];
    int selectedChapter = gameData.selectedChapter;
    int selectedLevel = gameData.selectedLevel;
    Levels *chapterLevels = [LevelParser loadLevelsForChapter:selectedChapter];

    //loop until we get selected level, then do stuff
    for (Level *level in chapterLevels.levels) {
        if (level.number == selectedLevel) {
            //load the level map
            _tileMap = [CCTMXTiledMap tiledMapWithTMXFile:level.file];
        }
    }

    _background = [_tileMap layerNamed:@"Background"];
    _foreground = [_tileMap layerNamed:@"Foreground"];
    _meta = [_tileMap layerNamed:@"Meta"];
    _meta.visible = NO;

    //initialize Spawn Point object and place player there
    CCTMXObjectGroup *objects = [_tileMap objectGroupNamed:@"Objects"];
    NSAssert(objects != nil, @"'Objects' object group not found");
    NSMutableDictionary *spawnPoint = [objects objectNamed:@"SpawnPoint"];
    NSAssert(spawnPoint != nil, @"SpawnPoint object not found");
    int x = [[spawnPoint valueForKey:@"x"] intValue] / retinaScaling;
    int y = [[spawnPoint valueForKey:@"y"] intValue] / retinaScaling;

    //setup animations
    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"MouseRightAnim_24x21.plist"];
    CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"MouseRightAnim_24x21.png"];
    [_mapLayer addChild:spriteSheet z:1];
    NSMutableArray *rightAnimFrames = [NSMutableArray array];
    for(int i = 1; i <= 3; ++i) {
        [rightAnimFrames addObject:
         [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:
          [NSString stringWithFormat:@"MouseRight%d_24x21.png", i]]];
    }
    CCAnimation *rightAnim = [CCAnimation animationWithSpriteFrames:rightAnimFrames delay:0.1f];
    self.player = [CCSprite spriteWithSpriteFrameName:@"MouseRight2_24x21.png"];
    _player.position = ccp(x, y);
    self.rightAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:rightAnim]];
    rightAnim.restoreOriginalFrame = NO;
    [spriteSheet addChild:_player];

    //get map size in pixels
    mapHeight = _tileMap.contentSize.height;
    mapWidth = _tileMap.contentSize.width;
    //setup defaults
    //this value works well for the calculation later, trial and error really
    distance = 150;
    lastGoodDistance = 150;
    mapScale = 1;

    [self setViewpointCenter:_player.position];

    [_mapLayer addChild:_tileMap];
    [self addChild:_mapLayer z:-1];

    self.isTouchEnabled = YES;
}
return self;
}

```

And here's the SceneManager code for replacing scenes:

```
+(void) goGameScene
{
    CCLayer *gameLayer = [GameScene node];
    [SceneManager go:gameLayer:[GameHUD node]];
}

//this is what every call looks like besides the GameScene one above
+(void) goLevelSelect
{
    [SceneManager go:[LevelSelect node]:nil];
}

+(void) go:(CCLayer *)layer: (CCLayer *)hudLayer
{
    CCDirector *director = [CCDirector sharedDirector];
    CCScene *newScene = [SceneManager wrap:layer:hudLayer];
    if ([director runningScene]) {
        [director replaceScene:newScene];
    }
    else {
        [director runWithScene:newScene];
    }
}

+(CCScene *) wrap:(CCLayer *)layer: (CCLayer *)hudLayer
{
    CCScene *newScene = [CCScene node];
    [newScene addChild: layer];
    if (hudLayer != nil) {
        [newScene addChild: hudLayer z:1];
    }
    return newScene;
}

```

Any ideas why I'm getting these fatal artifacts? I'm hoping this isn't considered too localized since it basically combines 3 tutorials that anyone could end up following. (Ray Wenderlich Animations, Tim Roadley Scene Manager, Pan and Zoom with Tiled Maps.

# Answer
> 0 votes
Found my problems.

I had to add `[super onExit]` to `onExit`. Missing this was causing `dealloc` to not fire.

I also had to **remove** the following lines from `dealloc`:

```
self.tileMap = nil;
self.background = nil;
self.meta = nil;
self.foreground = nil;
self.fogOfWar = nil;
self.mapLayer = nil;

```

They are all the ones related to the tilemap, and they were causing over-releases once I was able to hit `dealloc`. It's weird though; they're declared as `retain` in the header file.

---
Tags: cocos2d-iphone, ios, objective-c, tilemap
---