title: GLImpl.gldrawelements longer than usual

text:
# Question
Title: GLImpl.gldrawelements longer than usual
I'm developing a little game engine for the Android platform and I'm trying to improve the performance of this one. (I'm not an OpenGL expert) I can see a framerate drop sometimes, when using DDMS method profiling, I can see that the cause is a longer `GLImpl.gldrawelements` : the first one right after the `eglSwapBuffers`.

So my questions are : Do you have an idea why sometimes this call is longer? It seems that `GLImpl.gldrawelements` is waiting for something, am I right?

Why the first `GLImpl.gldrawelements` call (between two `eglswapbuffers` calls) is longer than the followings?

# Answer
> 3 votes
What you're seeing is the result of lazy state changes and your swapbuffers call flushing the pipeline.

In the first place, most drivers won't actually change state when you make a GL call; instead they just record the fact that you requested a state change (and may set a dirty bit to indicate that the state actually needs to be changed). Then, when a draw call happens, all of the recorded state changes are applied. The result of this is that your timings for any glDraw\* call may widely vary, some taking no time at all, some seeming to take a lot of time. If you're using VBOs it may be even more misleading as the timing may bear no relation whatsoever to the amount of geometry being drawn.

So if you've a lot of state changes queued up for that first draw call in a frame, then the glDrawElements may seem to take longer.

Secondly, any swapbuffers call will flush the pipeline, meaning that any queued up work will start to be processed. Because your glDrawElements call comes next, it may be waiting on that queued-up work to finish before it can proceed, so it would give aberrant timings if so.

You can test for and remove this factor from your timings by putting a glFinish call after your swapbuffers. This will (assuming your driver is conformant) complete all the outstanding work before it returns, so that it will no longer pollute your timings. If you have a bunch of CPU-side work you can do before the next frame runs, here is a good place to do it, as it can give the pipeline more time to complete it's flush before you start drawing stuff again.

In general however what you've got here is a classic case of CPU timings not being a good indication of what's actually happening on the GPU. Because a CPU and GPU operate asynchronously, all that you're measuring is the CPU-side times; you have basically got no valid data whatsoever for what's happening on the GPU.

---
Tags: opengl, android, performance
---


title: First Person Shooter vertical mouse aim

text:
# Question
Title: First Person Shooter vertical mouse aim
I've just started writing a 3D First Person Shooter in Java, and I'm having a bit of trouble with tracking the mouse movements and moving the camera accordingly. I'm implementing typical FPS movement, in that the mouse stays at the center of the screen.

Moving the mouse left and right (horizontal movement) is fine - each time the mouse is moved, I get it's position on the screen. I then use `atan2` to get the angle I need to rotate around the y axis to get to this position, and apply the rotation accordingly.

My problem is when I try to change the pitch of the view (i.e. rotating around the x axis - essentially looking up and down). I can get the y coordinate of the mouse, and the y coordinate of the center of the screen, but how do I calculate how much I need to rotate around the x axis to get to that point?

Thanks in advance!

# Answer
I don't know why you think you should use `Atan2`, but you shouldn't. And I'm surprised that you get anything that looks useful that way.

`double yRad = (mouseY-centerY)*sensitivityY;` Where `yRad` is the amount to turn, and the mouse is centred after the reading is really all there is to it.
> 1 votes

# Answer
Maybe your problem is not related to angle calculation, but the way you take your measurements.

Most FPS games use the following scheme:

* Read mouse position on screen
* Move mouse back to the center of the screen

This way, every frame you measure movement of the mouse, and not the position on screen. This allows for much more fluent and precise camera movement.
> 1 votes

# Answer
I'm not sure if I understand what you are trying to achieve. From my understanding, and from how I am doing it in my game, the usual thing is to calculate:

```
horizontalAngle += ( mousePositionOnScreenX - screenCenterX ) * sensitivityX;
verticalAngle   += ( mousePositionOnScreenY - screenCenterY ) * sensitivityY;

```

And then of course mouse is moved back to the centre.
> 0 votes

---
Tags: java, rotation, first-person-shooter
---


title: How to handle mouse input in XNA?

text:
# Question
Title: How to handle mouse input in XNA?
I am developing a card game in XNA.

Is there any `OnClick` event in XNA for objects?

I am trying to make cards move when the player clicks on them. In this project, there is a Sprite class that draws the card, but I am a little stuck because I don't know how to use `OnClick` events or anything like that.

# Answer
When working with XNA in general you have to move from an event driven code paradigm to a loop driven code paradigm. Your update code loops 60 times/sec. So each time, look at the state of the mouse and if a button is down & pointer is within your rect, then branch to code you would normally place in an OnClick event.
> 12 votes

# Answer
You'll need to implement it yourself. Try looking at the tutorial at: http://bluwiki.com/go/XNA\_Tutorials/Mouse\_Input
> 6 votes

# Answer
XNA only gives you just enough to build your own input classes - and you should do so considering the utility they offer.

I would recommend the mouse input class described in this blog post (source code). It detects a button being pressed, held or released, and lets you get that information either via polling or events.

On a related note, the same blog post also provides keyboard and gamepad input device classes.
> 6 votes

# Answer
The actual code for checking a mouse click in XNA is somthing like this;

```
    MouseState previousMouseState;
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        //store the current state of the mouse
        previousMouseState = Mouse.GetState();
    }

    protected override void Update(GameTime gameTime)
    {
        // .. other update code

        //is there a mouse click?
        //A mouse click occurs if the goes from a released state
        //in the previous frame  to a pressed state
        //in the current frame
        if (previousMouseState.LeftButton == ButtonState.Released
            && Mouse.GetState().LeftButton == ButtonState.Pressed)
        {
            //do your mouse click response...

        }

        //save the current mouse state for the next frame
        // the current
        previousMouseState = Mouse.GetState();

        base.Update(gameTime);
    }

```
> 3 votes

# Answer
If your game is 3D you can implement picking, which is described here: http://create.msdn.com/en-US/education/catalog/sample/picking\_triangle. Basically this creates a ray from the camera to where the mouse clicks (with a little matrix unprojecting in there), then you check to see if any of your objects were intersected by the ray.

If your game is 2D, you should be able to translate window coordinates to game coordinates fairly easily. Then check to see if the selected coordinates are within the bounds of any of your objects.
> 2 votes

# Answer
The simplest way to see if the mouse is clicked is this

```
//Create this variable
MouseState mouseState;

```

now in the update method add this

```
mouseState = Mouse.GetState();

if (mouse.RightButton == ButtonState.Pressed)
{
     //Do Stuff
}

```

hope this helped
> 1 votes

---
Tags: xna, c#, input, mouse
---


# Question
Title: Is it bad practice to set the velocity of an object every loop?
Say I have a simple game with a `gameLoop` function that gets called every 50 milliseconds or something similar, and I have a box2d object. Is it bad practice/too CPU intensive to use `SetLinearVelocity` on the object every time the `gameLoop` is called?

# Answer
It's only bad if you find this to be detrimental to the performance of your game. I find it unlikely that setting the velocity directly would be very expensive.

If you do find that this is an issue, by profiling the code, you can create a simple function that only updates the box2D object's velocity if your external velocity value has changed. Something like:

```
if(velocity != oldVelocity) {
    box2DObject.SetLinearVelocity(velocity);
    oldVelocity = velocity;
}

```
> 2 votes

---
Tags: box2d
---


title: 2D Software Lighting Issues in Java

text:
# Question
Title: 2D Software Lighting Issues in Java
I'm creating a 2D top-down tiled game in pure Java and by now I'm trying to implement a way to do lighting.

First, some details on how I render: there is a screen class which handles all the rendering. Pixels are put inside a `int[width * height]` array which is drawn on the actual screen using a `BufferedImage` and `Graphics.drawImage()`.

The way I am doing lighting right now is by creating a second `int[width * height]` array which holds all the brightness that should be subtracted from the actual pixels. I try to use only floats ranging from `0f` to `1f` to represent RGB intensities.

So, as an example, there is the ambient lighting which is 0.3f. What I do is a pixel to pixel operation, where for each pixel that will be drawn, its RGB values are decomposed, decreased 70% (1f - 0.3f), recomposed back into a single int and stored inside the secondary `int[width * height]` array. When transferring the pixels to the BufferedImage, I subtract the corresponding value inside the secondary array and get a darker image, as expected.

That was an example of darkening the image and it works fine, the problem appears when actually lighting them up: I gave the player a lightRadius and 3 light color component floats (RGB). While rendering the player, I also render it's lighting inside the secondary array by doing the following:

```
int mask = subtractMask[xx + yy * width];

int mr = (mask >> 16) & 255;
int mg = (mask >> 8) & 255;
int mb = mask & 255;

mr -= (int) (dist * light.r * mr);
mg -= (int) (dist * light.g * mg);
mb -= (int) (dist * light.b * mb);

subtractMask[xx + yy * width] = mr << 16 | mg << 8 | mb;

```

Where dist is a number ranging from `0f` to `1f` which makes the light fade with the distance from the source and `light.r/g/b` are each of the components of the light that comes from the player. What this piece of code does is basically to "give a little bit of the light that was taken out of a pixel back to it". As you can see, mr, mg and mb are made smaller (-=) and then composed back inside the number that will be subtracted from the corresponding pixel, thus making the result of the subtraction bigger (lighter). For white light I get the desired result: https://dl.dropbox.com/u/68532511/light1.png

The problem is when I only use the blue component (r = 0f, g = 0f, b = 1f), getting this: https://dl.dropbox.com/u/68532511/light2.png

Of course this can be explained by the fact that the tiles have very little blue values, making the ambient light take a little part of it away and making the lighting give this little part of it back (as you can see the biggest effect is on the player's pants, which are blue). What I still couldn't think of is a way to make lighting independent of how much brightness was taken away from the pixels and something that simply looks good in any way I combine the components (the result I expected for the second image was luminance like in the first one, but colored blue). So how can I implement such an effect?

Also, for making the lighting circular, I simply compute something light x^2 + y^2 \<= radius^2, where if this sentence is true, the pixel should light up, executing the code I've showed before. Is there a faster way to compute this? (I lost almost 50 FPS on this effect).

# Answer
> 1 votes
Physically, adding a colored light to a scene without any of that color will not illuminate the scene at all. Think about it in science terms: what you "see" in the real world is light reflecting off of various objects. In real-life, the light spectrum contains all colors... so the corresponding wavelength of light gets reflected off of objects and you "see" their color. However, if you restrict this spectrum, objects that absorb the corresponding colors won't reflect any back! A better way to think about this is that if you shine a pure blue light in a pure green room, you won't be able to see the walls!

That being said, I understand what you're trying to achieve in the game, and the best way to get what you're looking for is to use alpha compositing. Ideally, you can use this to generate the ambient effects that you want as well, and it will likely be faster than going through and modifying pixel values one by one.

For example, one way to darken your scene is to generate a black image with alpha 0.3, and composite it using `AlphaComposite.SRC_OVER`:

```
BufferedImage scene = ...;

int width = scene.getWidth();
int height = scene.getHeight();
int imgType = scene.getType();
BufferedImage blackImage = new BufferedImage(width, height, imgType);
Graphics2D blackImageGraphics = blackImage.createGraphics();
blackImageGraphics.setColor(new Color(0.0f, 0.0f, 0.0f, 0.3f));
blackImageGraphics.clearRect(0, 0, width, height);

Graphics2D sceneGraphics = scene.createGraphics();
sceneGraphics.setComposite(AlphaComposite.SrcOver);
sceneGraphics.drawImage(blackImage, 0, 0, width, height, null);

```

In order to add a colored "light" around your character, you can do a similar trick. First, render an image that's black and transparent everywhere except your "light" area, where you give a pixel value of whatever color you'd like your "light" to be, and an alpha value of, say, 0.5. Then, you can render this picture over your scene using `AlphaComposite.SRC_OVER` in exactly the same way as in the code above.

After you read the wikipedia article, you can find a lot of information regarding the different ways to play with alpha in Java by reading the documentation

---
Tags: 2d, java, graphics, lighting, pixel
---


# Question
Title: Choosing the correct isometric character facing direction
I am currently building a 3D game presented from a 2D isometric viewpoint.

The 3D coordinates start at the top left corner of the screen with x and y increasing towards the right and bottom edges respectively. An angle about the z axis starts with 0 facing right and increases CW.

The isometric coordinates use the diamond method seen in this reference:

My problem is related to choosing the correct frame for my characters. The characters each have a sprite sheet containing an image for one of the 8 compass directions. The start with the image facing right and rotate CW as in the 3D coordinates.

How can I choose the correct sub-image based on their rotation in 3D space? Is the problem is equivalent to converting the rotation into the isometric coordinate space?

# Answer
> 1 votes
Yes, the problem is the same as converting rotation to the isometric coordinate space. Though, it's somewhat simpler.

The primary "conversion" takes place by deciding how the rotation applies to the compass directions. For example, deciding that north is 0 degrees. Choosing the sprite to use is as simple as breaking a full 360 degrees in the the 8 compass directions.

See my answer here for an easy way to convert angle into compass directions.

---
Tags: rendering, isometric, coordinates
---


title: Getting correct angles between Vector3s

text:
# Question
Title: Getting correct angles between Vector3s
I'm working on a project where you can draw lines between points. You select one point and drag the mouse onto another point and a line is drawn between them.

The line itself is a 3d object which is scaled to match the length between points. Currently you can draw lines that are horizontal or vertical. But drawing a line that starts and ends on a different level fail.

Horizontal and vertical work well.

Here the lines should go like indicated by the grey lines. But it adds the Z-rotation(Up/down) to the Y-rotation(direction) - (Setting the Y-rotation by hand to match the horizontal line results the line being drawn correctly).

```
            Vector3 dir = junctionFinderHit.transform.position - startPos;  /// Direction vector
            float angleY = Vector3.Angle(dir, new Vector3(1, 0, 0));
            float angleZ = Vector3.Angle(dir, new Vector3(0, 1, 0));

            //Debug.Log(angleY + " - " + AngleDir(new Vector3(0, 1, 0), dir, Vector3.up));

            Vector3 rotationVector = new Vector3(0,0,0);

            if (AngleDir(new Vector3(1, 0, 0), dir, Vector3.up) < 0)    /// 360 movement instead of 180
                rotationVector.y = 360-angleY;
            else
                rotationVector.y = angleY;

            /// -90 degrees to make it horizontal by default, negative to make it point to the right direction
            rotationVector.z = (angleZ-90f)*-1;

            activeStick.transform.eulerAngles = rotationVector;

```

What do I need to do to get the rotations correct?

# Answer
Using the LookAt function is probably a better practical solution.

The reason that your code doesn't work is that your `angleY` calculation does not just get the angle in the horizontal plane, witch is what you need, but rather get the full angle including any vertical component. Projecting the direction on the horizontal plane before the calculation should solve the problem. I'm not able to test it, but I think this will give you the desired behaviour:

```
float angleY = Vector3.Angle(dir-Vector3.Project(dir,new Vector3(0, 1, 0)), new Vector3(1, 0, 0));

```
> 1 votes

# Answer
There's a simple solution. Don't use angles. Just draw the vertices for the objects starting at the start point and finishing at the end point.
> 0 votes

# Answer
I just implemented in C a way to calculate the angle between two vectors A,B, given an origin C. Look at this Wikipedia article to understand where I am coming from. Here's the pseudo-code:

```
/*
    A dot B = |A| * |B| * cos(theta)
    Therefor theta = acos (A dot B / |A||B|)
*/
double Vector3AngleBetweenTwoPoints(Vector3 p1, Vector3 p2)
{
    return acos(Vector3DotProduct(p1, p2) / (Vector3Magnitude(p1) * Vector3Magnitude(p2)));
}

double Vector3AngleBetweenABWithCOrigin(Vector3 A, Vector3 B, Vector3 C)
{
    return Vector3AngleBetweenTwoPoints(Vector3Subtract(A, C), Vector3Subtract(B, C));
}

```

It's probably not the "proper" Unity way to do it, but it should help you understand how to calculate the angle between two vectors (if that's really the question you want answered :P).
> 0 votes

---
Tags: c#, mathematics, unity, rotation, vector
---


title: 3D Collision Detection with XNA

text:
# Question
Title: 3D Collision Detection with XNA
So I'm trying to implement some collision detection in XNA. I'm aware of the Bounding Spheres, but I worry with the accuracy, most items in my game are cubic in nature, so it seems very square-peg in a round hole, so it seems to me bounding boxes would be the best solution.

I looked at having libraries(JigLibX, Henge3D) to do it for me, but most have heavy physics systems attached and that's really not what I'm wanting I've also tried to implement solutions utilizing the Vertex buffers for Bounding Boxes after XNA's importers and processors pack the .fbx model into the Content Pipeline to no avail.

So the two things I feel I'm left with are:

* Using Primitives as collisions "skins" for my objects.

+ Same problem here as using XNA's default bounding box, after Importation, I have no clue how to get it's size or even the vertices.
* Creating a Custom Content Processor to determine the vertices at Load, and then apply transformations to the Bounding Box along with the Model itself at run-time.

+ problem Here is that this is a very daunting task. I'm finding it hard to locate thorough documentation on XNA's default importer, so it's highly difficult to just create a custom Processor. I wouldn't even know how to begin to write my own importer.

TL;DR- I've hit a brick wall with 3D Collision using Bounding Boxes, Halp?

# Answer
> 1 votes
"Creating a Custom Content Processor to determine the vertices at Load, and then apply transformations to the Bounding Box along with the Model itself at run-time" is **not** a daunting task if you use the right algorithm.

You can use a custom ContentProcessor on your models that iterates through each vertex, look at their local positions and tracks the furthest ones on each axis. By doing so you can easily find the dimensions of the model and use it to make a BoundingBox object with the right dimensions. The thing is that you will need to update the size of the BoundingBox if you scale the model, which is not as difficult as it might seem since you just need to multiply the half of the box's dimensions by the scaling value.

# Answer
> 0 votes
You should be able to obtain the VertexBuffer after loading the model with the Content loader and through that obtain the actual vertices with a GetData() call. The only tricky part happens if there are bones in this particular model then you would have to apply the bone transformations to the child vertices in order that they would be scaled/translated appropriately. However, that said once you get the vertices and transformed them if needed, you simply do a little statistical analysis on them to determine the min/max for your x, y, and z. Use those values to create the 8 corners of your bounding cube and then make sure whenever you check for collisions that you apply the same transformation to the bounding cube that you did to your model.

---
Tags: xna, c#, 3d, collision-detection
---


# Question
Title: How do I prevent XNA from pausing Updates while the window is being resized/moved?
XNA stops calling `Update` and `Draw` while the game window is being resized or moved.

Why? Is there a way to prevent this behaviour?

(It causes my network code to desynchronise, because network messages aren't being pumped.)

# Answer
Yes. It involves a small amount of messing with XNA's internals. I've got a demonstration of a fix in the second half of this video.

**Background:**

The reason this happens is because XNA suspends its game clock when `Game`'s underlying `Form` is resized (or moved, the events are the same). This, in turn, is because it is driving its game loop from `Application.Idle`. When a window is resized, Windows does some crazy win32 message loop stuff that prevents `Idle` from firing.

So, if `Game` didn't suspend its clock, after a resize it will have accumulated an enormous amount of time that it would then have to update through in a single burst - clearly not desirable.

**How to fix it:**

There is a long chain of events in XNA (if you use `Game`, this doesn't apply to custom windows) that basically connects the resize event of the underlying `Form`, to `Suspend` and `Resume` methods for the game clock.

These are private, so you'll need to **use reflection** to unhook the events (where `this` is a `Game`):

```
this.host.Suspend = null;
this.host.Resume = null;

```

Here is the necessary incantation:

```
object host = typeof(Game).GetField("host", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
host.GetType().BaseType.GetField("Suspend", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(host, null);
host.GetType().BaseType.GetField("Resume", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(host, null);

```

(You could disconnect the chain elsewhere, you can use ILSpy to figure it out. But there's nothing else besides the window resize that suspends the timer - so these events are as good as any.)

Then you need to provide your own tick source, for when XNA isn't ticking from `Application.Idle`. I simply used a `System.Windows.Forms.Timer`:

```
timer = new Timer();
timer.Interval = (int)(this.TargetElapsedTime.TotalMilliseconds);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();

```

Now, `timer_Tick` will eventually call `Game.Tick`. Now that the clock isn't suspended, we're free to just keep using XNA's own timing code. Easy! Not quite: we only want our manual ticking to happen when XNA's built-in ticking doesn't happen. Here is some simple code to do that:

```
bool manualTick;
int manualTickCount = 0;
void timer_Tick(object sender, EventArgs e)
{
    if(manualTickCount > 2)
    {
        manualTick = true;
        this.Tick();
        manualTick = false;
    }

    manualTickCount++;
}

```

And then, in `Update`, put this code to reset the counter if XNA is ticking normally.

```
if(!manualTick)
    manualTickCount = 0;

```

Note that this ticking is considerably less accurate that XNA's. However it should remain more-or-less lined up with real time.

---

There is still one small flaw in this code. Win32, bless its stupid ugly face, stops essentially *all* messages for a few hundred milliseconds when you click the title-bar of a window, before the mouse actually moves (see that same link again). This prevents our `Timer` (which is message-based) from ticking.

Because we now don't suspend XNA's game clock, when our timer eventually starts ticking again, you'll get a burst of updates. And, sadly, XNA caps the amount of accumulatable time to an amount *slightly* lower than the length of time Windows stops messages when you click the title bar. So if a user happens to click and hold your title-bar, without moving it, you'll get a burst of updates *and* fall a few frames short of real time.

(But this should still be *good enough* for most cases. XNA's timer already sacrifices accuracy to prevent stuttering, so if you need *perfect* timing, you should do something else.)
> 20 votes

---
Tags: xna, c#, xna-4.0, win32
---


# Question
Title: Making a DX9 game resolution independent
How can I change the resolution and stretch my entire game to the new resolution? I want my game to have a base resolution, and when I change it to stretch to that new resolution. I saw a few similar questions but all the answers suggested that i should change the presentation parameters. If i do that, my screen resolution changes, but all my other objects remain the same size and draw in the wrong position.

I use a LPD3DXSPRITE object to draw the textures to the screen, some DirectX text, and vertices defined as this:

```
#define D3DFVF_VERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE)

```

I tried to put D3DXSPRITE\_OBJECTSPACE at sprite-\>Begin() and play with the projection, view and world matrices but without success.

Can someone tell me if this method is possible and how should I do it? I also read about another method that suggested rendering to a surface, and then stretching the surface, but i don't know how to implement that. I am a beginner in DirectX. I googled the second method, but I couldn't find someone explaining it, and I don't think I can draw from a sprite to a surface.

# Answer
You can use the direcx 9 function SetRenderTarget (http://msdn.microsoft.com/en-us/library/windows/desktop/bb174455(v=vs.85).aspx) to specify any number of renderable targets you want. This would typically be set to a buffer, and that buffer would be swapped with the front buffer to produce what is known as double buffered rendering.

What you are wanting to do is render the game at a different resolution though, despite the resolution of the window you are in, correct? For this, you could adjust the size of your viewport, which adjusts the resolution that is rendered to your render target. This is independent of the window resolution, but could yield unsavory results if the correct aspect ratio is not maintained.

Viewport Info http://msdn.microsoft.com/en-us/library/windows/desktop/bb206341(v=vs.85).aspx
> 1 votes

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


# Question
Title: How to cover the widest range of computers when publishing?
When you plan a game, or even when you already made a game, and its time to publish, you wonder how much of your audience is covered by the game technology demands.

I'm directing this essentialy to casual games, as I constantly see people having old laptops and being unable to replace them. Laptops with integrated cards whose OpenGL version doesn't even support textures larger than 1024x1024. These people may be avid gamers as well, and a reasonable share of the audience to consider giving them the chance to play casual games, once they cannot play any blockbusters.

As I've seen happening, a very "noticeable" example is Angry Birds. It's gameplay is merely casual (I think nobody disagrees here) and still, it uses so high resolution textures that at least OpenGL 2.0 or around is needed, which blocks away a lot of people.

So, the actual question is: what is a good tradeoff for this issue? Would it be better to just sacrifice the texture resolution for everyone, but have more supported hardware? Would it be better to keep the high quality and just slice the textures into smaller ones, sacrificing the performance a little bit? What else?

Any ideas about this topic are welcome for discussion.

# Answer
> 6 votes
"It depends."

On a lot of factors.

First, there's the game style. If you're making Angry Birds 2 then, yeah, it would probably be in your interests to make sure it runs on everything. Your target audience may have a rather crummy computer and the larger you can cast the net, the better. Conversely, if you're making Quake 6: Gorestone Bloodbath, then you can probably get away with not running on a five-year-old platform. Your target audience wouldn't be caught dead with anything that old.

Second, there's the sheer game requirements. If you're making Angry Birds *3* and your design doc requires that each individual plank of wood be able to split apart into properly-simulated splinters, then your users will have to have a good *computer*, and therefore you can probably rely on your users have a reasonably good graphics card. (Especially with the new Intel integrated graphics.) Conversely, if you're making Bejeweled 3 . . . well, you could run Bejeweled on a wristwatch, so you don't get a free pass to say "yeah, we'll just require more".

Finally, there's your own resources. A one-man game studio doesn't have much time to spend to make sure the game functions on absolutely everything under the sun - it may be perfectly sensible to say "okay, we're going to require opengl 2.0, we'll pop up an error message that recommends updating drivers, we're just going with that." Conversely, if you're a 200-person AAA studio, you may find yourself doing compatibility tests on specific individual network cards.

In the case of Angry Birds, I would personally implement a fallback to split high-res textures apart, at the cost of some efficiency, and go with that. If I found that a significant number of users were hitting the fallback and then having a bad game experience - but not *such* a bad game experience that I felt it was unsolvable - then I might spend time on a better fallback. But I'd be spending far more time making a good game than trying to eke out percentage points of potential market share. A great game that 95% of humanity can play will sell a hell of a lot more than a mediocre game that 99% of humanity can play.

And finally, if you're an indie developer making artistic games, remember that the long tail is your friend. If your game is great, ten years from now people will *still* be buying it, and your "OpenGL 2.0, 2gb of RAM required" message will seem laughable compared to the bargain-basement 256gb RAM OpenGL 6.0 machines that Wal-Mart will be selling. I don't think this applies as much to the AAA or casual markets, though.

# Answer
> 0 votes
Just look at what the big games do. They have the ability to scale. Some automatically, some manually.

Detect the capabilities of the platform you're trying to run on and adapt as best you can. Maybe ship with assets at different levels of detail and use the highest you can.

# Answer
> 0 votes
Look at titles like World of Warcraft, do more artistically with fewer polys and shaders. My favorite example of this is the draw distance in the original Silent Hill, through the use of careful design most players barely notice the actual draw distance being so low, they are aware of it only as a game element.

# Answer
> 0 votes
Always remember, who is your target audience.

If your game is a new fps, you can probably start working in it assuming DX11, just because anyone that plays fps games will put up with that restriction or already have upgraded.

If your game is casual, slow paced, your technology needs to be centred differently. Possibly around the idea of lowest common denominator hardware.

The point is: who are you trying to sell the game to?

In your question you allude to the audience being more casual gamer, in which case, find the lowest spec you are willing to work to, and then make the best game you can within those limits. Making a game that scales its graphical beauty with the spec of the machine detracts time from making your game pretty at all levels of tech. The best example I can think of is Plants Vs Zombies. There's no "super graphics" mode, and that's because the game was designed to be pretty without resorting to tech.

# Answer
> 0 votes
Use Direct3D 9, not OpenGL.

That way you get to work on those machines with integrated graphics which have bad OpenGL support, you get to work on machines with OEM drivers that don't even have OpenGL support, and you get to spend less time dealing with driver bugs from AMD and Intel.

True, your platform support is now limited to Windows (although WINE may help some) but the number of computers you will potentially work on will be higher.

---
Tags: hardware-acceleration
---


title: Create cylinder using OpenGL-ES

text:
# Question
Title: Create cylinder using OpenGL-ES
I want to draw cone using OpenGL ES I have gone through many links to draw cylinder but I don't have any idea or approach to draw the cylinder. I've seen the `gluCylinder` function for OpenGL, but no equivalent function in OpenGL-ES.

i tried the below code

```
float radius, halfLength;
int slices;
for(int i=0; i<slices; i++) {
    float theta = ((float)i)*2.0*M_PI;
    float nextTheta = ((float)i+1)*2.0*M_PI;
    glBegin(GL_TRIANGLE_STRIP);
    /*vertex at middle of end */ glVertex3f(0.0, halfLength, 0.0);
    /*vertices at edges of circle*/ glVertex3f(radius*cos(theta),
    halfLength, radius*sin(theta));
    glVertex3f (radius*cos(nextTheta), halfLength, radius*sin(nextTheta));
    /* the same vertices at the bottom of the cylinder*/
    glVertex3f (radius*cos(nextTheta), -halfLength, radius*sin(nextTheta));
    glVertex3f(radius*cos(theta), -halfLength, radius*sin(theta));
    glVertex3f(0.0, -halfLength, 0.0);
    glEnd();
}

```

# Answer
> 2 votes
Basically the formula would be as follows :

(assuming Y points up)

you need to declare "slices", "HEIGHT", r

x- origin of the bottem circle on X axis

y- origin of the bottem circle on Y axis

z- origin of the bottem circle on Z axis

```
glBegin(GL_TRIANGLE_FAN);
// bottom circle
glVertex3f(x,y,z);
for(int i=0, float alpha=0; i<slices; i++) glVertex3f(x + cos((float)i/slices * 2 *PI)*r,
y, z+sin((float)i/slices * 2 * PI)*r);
glEnd();

glBegin(GL_TRIANGLE_FAN);
//top circle
glVertex3f(x,y + HEIGHT,z);
for(int i=0, float alpha=0; i<slices; i++) glVertex3f(x + cos((float)i/slices * 2 *PI)*r,
y+ HEIGHT, z+sin((float)i/slices * 2 * PI)*r);
glEnd();

// the rest
glBegin(GL_TRIANGLE_STRIP);
for(int i=0, float alpha=0; i<slices; i++)
{
   glVertex3f(x + cos((float)i/slices * 2 *PI)*r,y, z+sin((float)i/slices * 2 * PI)*r);
   glVertex3f(x + cos((float)i/slices * 2 *PI)*r,y+ HEIGHT, z+sin((float)i/slices * 2 *      PI)*r);
}
glEnd();

```

This should be just fine

---
Tags: iphone, ios, opengl-es
---


# Question
Title: Weird stuttering with fixed-timestep, variable-framerate game loop
I've been trying to set up fixed-timestep loop for my game, using the technique from here. I have no need for the interpolation step as I intend to run the logic at or above vsync speed.

Here is a simplified version of my test code (C#):

```
const double MILLISECONDS = 1000.0;
const double TARGET_SPEED = 60.0; //Logic tick rate in hertz

const double dt = MILLISECONDS / TARGET_SPEED;

double currentTime;
double accumulator = 0.0;
Stopwatch logicTimer = new Stopwatch();

double theta = 0;
float spinSpeed = 0.005f;

//Game loop:
while (true)
{
    double newTime = logicTimer.ElapsedMilliseconds;
    double frameTime = newTime - currentTime;

    currentTime = newTime;
    accumulator += frameTime;

    while (accumulator >= dt)
    {
        theta = (theta + spinSpeed * dt) % (Math.PI * 2.0);
        accumulator -= dt;
    }

    //Draw sprite, rotated theta radians
    Draw();
}

```

With TARGET\_SPEED at 60Hz on a 60Hz monitor, most of the time it runs smoothly. However, often when I run the test I see periodic jumps in the rotation. The time to complete a revolution does not change, but it appears to stand still for an extra frame or two and then jump ahead to make up the difference. The frequency of these stutters is constant during a run, but subsequent runs with the same settings will stutter at different rates.

I've measured how much theta changes each logic step, and it's rock steady across multiple runs regardless of stuttering.

This leads me to believe the problem is something to do with differences between my game's clock and my monitor's refresh clock. However, I can't figure out anything beyond that.

The problem still happens whether vsync is on or off. It happens less often when TARGET\_SPEED is a multiple of 60; for any other value it happens on every run. Increasing TARGET\_SPEED past 1000 or 10,000 Hz appears much smoother, but there's no way I can run a real game that fast. Drawing more or fewer sprites to control the time spent rendering doesn't seem to have any consistent effect on the problem.

So basically I'm completely stumped. Any idea why this is happening and how I can fix it?

Here's the full source file for my test project (XNA) if you want to try it for yourself.

# Answer
> 1 votes
Maybe the problem lies elsewhere in the code, but if you're sure it's contained in the code you pasted, and the stutter is periodic, constant, and only happens in some tests (but constantly throughout the execution), you might be dealing with a rounding error, which would happen only if the initial time gets initialized to a specific value.

I see you're using doubles, but the MSDN documentation says that `Stopwatch.ElapsedMilliseconds` returns `long`. So I'd first change all time variables to `long` (yes even the `dt`, round it down to the nearest value), and see if the problem disappears.

Also, I don't know about XNA, but the modulo operator is for integers only, and to make it work with floating point values (and PI\*2 will be a floating point value), instead of:

```
theta = (theta + spinSpeed * dt) % (Math.PI * 2.0);

```

You want fmod():

```
theta = fmod(theta + spinSpeed * dt, Math.PI * 2.0);

```

*Tip: you might want to define a constant for `Math.PI * 2.0` to save a couple of CPU cycles.*

---
Tags: xna, game-loop, vsync
---


title: Rotation matrix from OpenGL to DirectX

text:
# Question
Title: Rotation matrix from OpenGL to DirectX
I have an application which uses openGL and i have to port it to DirectX. To sum up my issue : How can I port rotation matrix based on a right-handed coordinate system to a left-handed coordinate system ? I hardly found some documentation on the internet.

This is what i found on MSDN:

* Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
* Use the view matrix to scale world space by -1 in the z-direction. To do this, flip the sign of the \_31, \_32, \_33, and \_34 member of the D3DMATRIX structure that you use for your view matrix.

This is work fine except i can not flip easily my vertices because i got an 3D model from CATIA which is not a primitive, so i can't use it.

(I'm aware of row-major and column-major difference, it does not matter)

Do you know how i can port my rotation matrix from openGL to DirectX ?

Thanks a lot

# Answer
> 1 votes
I believe, the only difference (besides row/column majorness) is that DirectX uses lefthanded coordinate system and openGL uses righthanded system. You simply need to flip one base vector. Rotation matrix (r) is just a definition of those vectors. So making

```
r._31 = -r._31;
r._32 = -r._32;
r._33 = -r._33;
r._34 = -r._34;

```

will just flip the z-coordinates.

The other problem is the triangle ordering (and Front/Back face culling). If you can turn backface-culling off (or switch to frontface-culling), you are OK.

---
Tags: opengl, directx
---


title: Android activities, when to use them?

text:
# Question
Title: Android activities, when to use them?
I'm getting back into programming my game and I can see that I've used activities for so many things. I only have one with a custom-view (my actual game), the others are activities with XML-views, like menus, level-selector, Complete-screen etc.

My question is, Should I not use acitvities for this? and instead create states in my game with different touch-listeners? because I'm afraid of memory-leaks, which tends to come with the use of having activities everywhere.

I destroy all the activities properly before I move onto the next, but still, it feels sloppy somehow. Maybe the startscreen and levelselector are ok, since they are not called in real-time. But my complete-screen is called in real-time through the UI-thread, this just feels wrong.

My heap is already out of control and I dont need any leaks, I already have to limit my app to androids from 2012 and beyond.

So I'm calling out to someone with experience, since this is my first really big game, that I intend to release.

also, if anyone can tell me what these rows that I get in my logcat means, I would really appriciate it, I get that it has to do with heap and allocations, but what is good/bad to have here?

`03-20 02:26:23.142: D/dalvikvm(21837): GC_FOR_ALLOC freed 941K, 8% free 14613K/15815K, paused 15ms, total 15ms`

`03-20 02:26:23.158: I/dalvikvm-heap(21837): Grow heap (frag case) to 17.825MB for 3686416-byte allocation`

`03-20 02:26:23.181: D/dalvikvm(21837): GC_CONCURRENT freed <1K, 7% free 18212K/19463K, paused 13ms+3ms, total 28ms`

# Answer
Well, starting with the log lines you posted: those basically tell you that you don't have memory leaks "per-se" - you can't really have that with Java (well you can with Android Java if your'e careless with certain resources like image loading, but for most of the time you're fine).

What those lines describe is that at some point the garbage collector freed up some memory (line 1), than it follow by telling you that, from the whole chunk of memory available to your application an extra chunk has been made "active" (allocated as heap because instantiating something has made the previously allocated heap almost full) and finally the 3rd line is another garbage collect call which frees up some memory.

The Java-like "memory leaks" you can get with Android (and really any Java program) are really very different than those you can get with unmanaged languages (like C++): with C/C++ you get a memory leak if you consistently forget to free memory that you've manually allocated to instantiating some objects. With Java you can't manually allocate memory (the "new" operator in Java does this behind the scenes) and you absolutely have no way to manually free used memory (you can hint at it, but that's it). Since Java's heap is "freed" by the Garbage Collector automatically (and based on its own internal algorithms), what you can get is: if you create a lot of new objects in a short time (instead of reusing existing instances as much as possible), the Garbage Collector will be called more often to free your memory (followed by a behind-the-scene reallocation of heap for the new objects) and this can take time. It can get to the point where the GC uses 10-15% of the application CPU time, and results in visible slowdowns. Obviouslly, the first and easiest way to avoid this is to reuse your already created objects as much as possible (instead of creating new ones).

Coming back to your actual question: normally, the number of Activities you create will not have a dramatic impact on memory consumption and garbage collection time. That being said, you should balance the number of actual activities you have between having a decent logical organisation of your project and a decent GC occupation. Basically if your app has a handful of screens, you should make each one as a separate action. If however you find yourself making actvities for very small elements, which can just as well be displayed as pseudo-pop-ups and/or dialogs in an existing action, is better to refactor that code and "merge" those multiple small activities into a single one (with state-driven for the display of each of the contents of the previous activities).

The idea here is to make sure that:

* there's really a lot of memory being used up and that's really an issue (you actually notice slowdowns because of it)
* the extra memory is really due to action instanciation, and not due to other parts of your code (which create other types of instances)
* try not to cut down to drastically on your activities, as this may also negatively impact your app: normally the OS deals with "passivation" and unloading of activities from memory when they're not used. However if everything is happening in one action, even if some contents is not needed at a given time, the OS will no longer be able to unload it
> 3 votes

---
Tags: java, android, game-design
---


title: Swarm/crowd movement with box2d?

text:
# Question
Title: Swarm/crowd movement with box2d?
Apart from using b2Body::setTransform(), are there other ways to move a body around while keeping its dynamics ?

I want to move several bodies at the same time into one direction, pretty much like the movement of a crowd like the units in starcraft 2.

Does box2d already provide such features, if yes what is this called ? If not what precautions should I take while using setTransform ?

# Answer
This would be the same as implementing a boids algorithm, and using Box2D to apply the forces required:

* Separation: Steer to avoid crowding local flockmates
* Alignment: Steer towards the average heading of local flockmates
* Cohesion: Steer to move toward the average position of local flockmates

You can see an example in action here and get some details on its implementation here.

Applying the forces would be with Box2D functions to apply forces or impulses. You can read up of those here.
> 2 votes

---
Tags: c++, 2d, physics
---


# Question
Title: How should I calculate the new angle/direction of my ball hitting a wall?
I'm building a Pong game and I am stuck at how the ball should bounce when hitting a horizontal wall. I tried a few methods but none seems to work.

So far I have an update method, which is called every 15ms and which does this:

```
float scale_x = Math.Cos(ball._angle).ToFloat();
float scale_y = Math.Sin(ball._angle).ToFloat();

//speed multiplied by scale_x is our x velocity
float velocity_x = (gameSpeed * scale_x);

//speed multiplied by scale_y is our y velocity
float velocity_y = (gameSpeed * scale_y);

ball._vector.x += velocity_x;
ball._vector.y += velocity_y;

```

and if the ball hits the horizontal wall

```
if (ball._vector.y + velocity_y < 0){
    Vector n = new Vector(ball._vector.x, ball._vector.y);
    n.nor();

    float dot = (ball._vector.dot(n));
    ball._vector = ball._vector.add(n.mul((-2 * dot)));
}

```

I've been using this formula `R = 2 * (V dot N) * N - V` to calculate the new direction. But I can't seem to get it to work. To be honest, I'm not sure what kind of formula I need. I just need to find the new angle when it hits the wall.

Here is the solution for my game. first i made velocity\_x and y instance variables.

```
private float velocity_x;
private float velocity_y;

```

then i sat the start for my direction in my constructor

```
float scale_x = Math.Cos(ball._angle).ToFloat(); //The x scale is the cosine of the angle
float scale_y = Math.Sin(ball._angle).ToFloat(); //The y scale is the sin of the angle

velocity_x = (gameSpeed * scale_x); //speed multiplied by scale_x is our x velocity
velocity_y = (gameSpeed * scale_y); //speed multiplied by scale_y is our y velocity

```

Finally in my updateBall method i leave:

```
ball._vector.x += velocity_x;
ball._vector.y += velocity_y;

```

# Answer
If what you're looking for is a simple reflection to a horizontal surface, then all you have to do is flip the y-component of the velocity vector depending on the normal of the surface you're hitting.

```
if(collision_horizontal){
    velocity_y = -velocity_y;
}

```

similarly:

```
if(collision_vertical){
    velocity_x = -velocity_x;
}

```
> 2 votes

# Answer
The formula `R = 2 * (V dot N) * N - V` requires normalized vectors for N, in order to calculate the new direction.

`V` would be a 2-dimensional vector defining the velocity or direction the ball is travelling in (in your case scale\_x/y or velocity\_x/y)

`N` defines the normal vector (length=1) of the collision plane. E.g. `(0,1)` for a horizontal plane and `(1,0)` for a vertical plane.

This will yield `R`, the reflected velocity vector, or the new direction

Using this formula would be overkill however, since you are only colliding with horizontal (and I expect vertical) planes. So I would suggest flipping the respective component of your velocity vector. For a horizontal plane this would be the y-component, for a vertical plane the x-component.

Another thought: Is there a specific reason why you are working with an angle for the direction of the ball? Cos and Sin is usually not good for performance and should be avoided (although in the case of pong it is probably negligible). I would try to use a direction vector instead.
> 2 votes

# Answer
If you simply need a new angle when a barrier is hit then:

```
[new angle] = 2*[barrier angle] - [old angle]

```

In order to cap it to the normal range you should implement that as:

```
[new angle] = ( 2*PI + 2*[barrier angle] - [old angle] ) mod 2*PI

```

Assuming radians, if you use degrees then you should use 360 instead of 2\*PI.
> 0 votes

---
Tags: c#, collision-detection, physics
---


# Question
Title: Emulate border color texture address mode efficiently
In WinRT the border color texture address mode is not supported.

The best I came up with in emulating the border address mode, is doing this in my pixel shader:

```
float4 tcol = tex.Sample(texSampler, texCoord);

if(texCoord.x < 0 || texCoord.y < 0 || texCoord.x > 1 || texCoord.y > 1)
  tcol = borderColor;

```

But as only `ps_4_0_level_9_1` is supported as minimum requirement in WinRT, this conditional in the pixel shader is quite inefficient.

How would I emulate border texture addressing mode efficiently?

# Answer
> 2 votes
Although it was just a guess, the following method seems to work:

1. Shrink your texture by one pixel in all directions
2. Manually add a red border
3. Set the texture wrapping mode to clamp

---
Tags: directx, directx11
---


title: How to avoid gimbal lock

text:
# Question
Title: How to avoid gimbal lock
I am trying to write code with rotates an object.

I implemented it as:

Rotation about X-axis is given by the amount of change in y coordinates of a mouse and Rotation about Y-axis is given by the amount of change in x coordinates of a mouse.

This method is simple and work fine until on the the axis coincides with Z-axis, in short a gimble lock occurs.

How can I utilize the rotation arount Z-axis to avoid gimbal lock.

# Answer
The simple solution is not to store the orientation of the object as angles around axes (X-, Y-, Z-axis), as for instance in euler angles.

Store the orientation of the object as a matrix or a quaternion.

This can cause gimbal lock, using euler angles:

```
class Object
{
    float m_angleAxisX;
    float m_angleAxisY;
    float m_angleAxisZ;
};

```

No gimbal lock:

```
class Object
{
    matrix m_orientation;
};

```

No gimbal lock either:

```
class Object
{
    quaternion m_orientation;
};

```

Now whenever the mouse is changed, multiply m\_orientation with the orientation change coming from the mouse movement each frame.
> 17 votes

# Answer
This book (real-time rendering) helped me alot! See on page 66 and 70. It has very good graphics and explenation. Quaternions are on page 72 aswell! :)

Rotation about an Arbitrary Axis

This renders the camera with the rotation done by mouse input:

```
void Camera::getVectors(D3DXVECTOR3& up, D3DXVECTOR3& lookAt)
{
    float yaw, pitch, roll;
    D3DXMATRIX rotationMatrix;

    // Setup the vector that points upwards.
    up.x = 0.0f;
    up.y = 1.0f;
    up.z = 0.0f;

    // Setup where the camera is looking by default.
    lookAt.x = 0.0f;
    lookAt.y = 0.0f;
    lookAt.z = 1.0f;

    // Set the yaw (Y axis), pitch (X axis), and roll (Z axis) rotations in radians.
    pitch = m_rotation.x * 0.0174532925f;
    yaw   = m_rotation.y * 0.0174532925f;
    roll  = m_rotation.z * 0.0174532925f;

    // Create the rotation matrix from the yaw, pitch, and roll values.
    D3DXMatrixRotationYawPitchRoll(&rotationMatrix, yaw, pitch, roll);

    // Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
    D3DXVec3TransformCoord(&lookAt, &lookAt, &rotationMatrix);
    D3DXVec3TransformCoord(&up, &up, &rotationMatrix);
}

// The Render function uses the position and rotation of the camera to build and update the view matrix
void Camera::render()
{
    D3DXVECTOR3 up, position, lookAt;

    // Setup the position of the camera in the world.
    position = (D3DXVECTOR3)m_position;

    getVectors(up, lookAt);

    // Translate the rotated camera position to the location of the viewer.
    lookAt = position + lookAt;

    // Finally create the view matrix from the three updated vectors.
    D3DXMatrixLookAtLH(&m_viewMatrix, &position, &lookAt, &up);

    return;
}

```

With the mouse input you modify yaw(head), pitch and roll.
> 0 votes

---
Tags: camera, rotation
---


# Question
Title: Using 4096*4096 background image in uinty tk2d
I am new to Unity and I am developing a game using unity its a 2d game i am using tk2d framework. I have a big background image(4096\*4096) how can I load this background so only visible part of the background has to be rendered so it wont effect the performance. How can I achive this in unity & tk2d?

# Answer
You're going to have to break up the image into multiple sections. Probably 1024x1024 for maximum compatibility (source). Then you can just place them in the background in order.
> 1 votes

---
Tags: unity, iphone, performance
---


# Question
Title: Server fixed timestep not running at 30Hz but way way too fast
I'm trying to make my game's server thread run at a fixed 30Hz but can't figure out how. Basically, before I just had a stupid while(1) { //do everything as fast as you can} which means that for my computer, with client and server on localhost, results in sending ~30,000(!) packets *per second*. which of course, is way, way too much.

Which is all because it's burning as fast as it can, and since the player position is being changed extremely quickly, it will send out those packets just as quickly.

It's based off of the infamous fixed timestep: http://gafferongames.com/game-physics/fix-your-timestep/ but I'm trying to use C++11's chrono features, but anything I try to do still doesn't slow down the server. Either it won't *ever* run the inner while loop, or it will do so (like it does right now with the code below), super super fast-like.

The problem's definitely something simple/stupid, but I can't tell what.

Thanks.

```
std::chrono::system_clock::time_point currentTime = std::chrono::high_resolution_clock::now();
double accumulator = 0.0;
const double dt = (1.0 / 30.0) / 1000.0 / 1000.0; // runs at 30 hz
double t = 0.0;

while (1) {

    std::chrono::system_clock::time_point newTime = std::chrono::high_resolution_clock::now();
    double frameTime = std::chrono::duration_cast<std::chrono::nanoseconds>(newTime - currentTime).count();

    if ( frameTime > 1.0/15.0 / 1000.0 / 1000.0) {
        frameTime = 1.0/15.0 / 1000.0 / 1000.0;   // note: max frame time to avoid spiral of death
    }
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        m_world->update(dt);
        poll();

        t += dt;
        accumulator -= dt;
    }

    const double alpha = accumulator / dt;

    // do network shit
}

```

# Answer
Your game loop code is correct, but your units are all mixed up -- you are effectively setting to your timestep to .00000003 nanoseconds!

Your clock is counting in nanoseconds, so your dt should be in nanoseconds. If a clock ticks 30 times a second, it will tick every .033 seconds. There are many nanoseconds in a second, so it will take more nanoseconds to tick (\* 1000.0), not fewer (/ 1000.0). Your code should work if you change your dt to this:

```
const double dt = (1.0 / 30) * 1000 * 1000 * 1000;   // 1000ms in s, 1000μs in ms, 1000ns in μs

```

and make a similar change for your max frame cap:

```
if ( frameTime > 1.0/15.0 * 1000.0 * 1000.0 * 1000.0) {
    frameTime = 1.0/15.0 * 1000.0 * 1000.0 * 1000.0;   // note: max frame time to avoid spiral of death
}

```
> 5 votes

---
Tags: algorithm, networking, game-loop, fixed-timestep, c++
---


title: TCP vs. UDP on mobile platforms?

text:
# Question
Title: TCP vs. UDP on mobile platforms?
I am designing a mobile game, but I don't know much about it.

How do we differentiate HTTP, TCP and UDP in reference to mobile game?

# Answer
HTTP is just another protocol on top of TCP, therefore I'll skip it in my answer. Use HTTP only for infrequent simple notifications like highscore uploads.

Beej has a good tutorial on TCP and UDP socket programming: http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html

Basically TCP is a connection oriented protocol. A client connects to a server, they exchange some messages, one of them closes the connection. You can think of it as a bytestream flowing directly from one side to the other. TCP makes sure no byte gets lost and all of them arrive in order.

UDP doesn't provide anything of this. It is very low-level. You just send a bunch of bytes (message) to some destination (address). UDP will build a packet out of these and send it on its way. There is no guarantee it will ever arrive.

For high-performance multiplayer games you need UDP, because you can't afford the latency overhead of TCP. But you have to handle all of those cases where packets get lost, duplicated or reordered yourself.

If latency is not of concern go for TCP. It is *much* easier to use.
> 4 votes

# Answer
On Stack Overflow there's an answer that says that mobile carriers don't allow UDP:

https://stackoverflow.com/questions/5861009/realtime-multiplayer-game-over-mobile-network

That would appear to make it open and shut: only TCP is viable, if that answer is correct.
> 3 votes

# Answer
One key difference between UDP and TCP is, for lack of a better phrase, "ownership of receipt".

In UDP the receiver is responsible for guaranteeing receipt of all required messages. This is particularly useful for streaming media content, becuase in most cases if a message is lost the receiver doesn't care; the frame is past history and had a spot of snow. No harm no foul.

In TCP the sender is responsible for guaranteeing delivery, so if no acknowledement is received before timeout the message is resent. There is greater overhead on both sides, plus greater traffic in the form of all the acknowledgements; but the benefit is a more reliable delivery.
> 3 votes

# Answer
UDP is difficult; you can typically only use UDP for client-initiated messages.

Also, TCP is also particularly high latency for mobile. And its very bursty; it might be running very fast and suddenly it drops right off.

But TCP works pretty much across the board.

There is no widespread peer-to-peer networking for games; all gets bounced through a central server.

You can do fun peer-to-peer stuff using any platform-provided push mechanism e.g. C2DM on Android, but that only suits turn-based slow games.
> 1 votes

---
Tags: networking, mobile
---


# Question
Title: How do I convert between two different 2D coordinate systems?
I'm trying to convert a coordinate from one coordinate system to another, so that I can draw it on an image.

Basically the destination coordinate system is as follows:

```
X range: 0 to 1066
Y range: 0 to 1600

```

(just a standard image I'm drawing onto with the size of 1066 x 1600)

The position I'm trying to draw onto the image actually has the exact same size, but the coordinate system is different. The span all of the coordinates is 1066x1600.

But a coordinate example would be:

```
(111.33f, 1408.41f)
(-212.87f, 1225.16f)

```

The range of this coordinate system is:

```
X range: -533.333 to 533.333
Y range: 533.333 to 2133.333

```

I feel like this is VERY simple math, but for some reason I'm not getting it.

How can I convert the coordinates provided into the first coordinate system?

# Answer
> 7 votes
You can normalize the first value, this will give you a value in the \[0,1\] range. You can think of that as X percentage, the percentage the value maps to between the minimum and maximum values. Then you can find where that percentage belongs in your destination coordinate system by seeing what value is X percentage through the destination system. I'll use Java code as an example language, I'm sure the concepts are clear enough to translate to any language though.

So normalize:

```
public static float normalize(float value, float min, float max) {
    return Math.abs((value - min) / (max - min));
}

```

Using your example you'd input:

```
xPercent = normalize(x,0,1066);

```

Then find where it lays in the destination system. With something like

```
destX = xPercent*(Math.abs(max-min)) + min;

```

Or to use your values:

```
destX = xPercent*(Math.abs(533.33--533.33)) + -533.33;

```

So for example with an x value of 1000 you'd map that to your destination coordinate system to `467.29`.

**Alternatively**, if the coordinate systems will always be the same, you can pre-compute the ratio between them.

So:

```
xRatio = (Math.abs(srcMax-srcMin))/(Math.abs(destMax-destMin));

destX = x*xRatio+destMin;

```

# Answer
> 4 votes
It is simple math:

```
res = ( src - src_min ) / ( src_max - src_min ) * ( res_max - res_min ) + res_min

```

src - source coordinate system

res - result coordination system

**Edit - explanation of math**

`( src - src_min ) / ( src_max - src_min )` translates it to coordinate system starting at zero with equal length of source coordinate system `(0.0, src_max - src_min )`. Then it scales value to coordinate system `(0.0, 1.0)`.

`* ( res_max - res_min )` this scales value to coordinate system starting at zero with length of result coordination system `(0.0, dst_max - dst_min)`

`+ res_min` translates value to result coordinate system `(dst_min, dst_max)`

# Answer
> 3 votes
The basic equation for 2D coordinate tranformation (in algebra, without rotation involved) is:

```
TargetCoordinate = TranslateFactor + ScalingFactor*SourceCoordinate

```

given two points in TargetCoordinate (T1, T2) that corresponds to two points in SourceCoordinate(S1, S2), `TranslateFactor` and `ScalingFactor` is given by solving :

```
T1 = TranslateFactor + ScalingFactor*S1
T2 = TranslateFactor + ScalingFactor*S2

```

which result :

```
TranslateFactor = (T2*S1 - T1*S2) / (S1 - S2)
ScalingFactor   = (T2 - T1) / (S2 - S1)

```

In your case, for the x coordinate

```
S1 = 0    -> T1 = -533.333
S2 = 1066 -> T2 = 53.333

```

And thus,

```
TranslateFactor = -533.333
ScalingFactor   = 1.000625
=> TargetCoordinate = (-533.333) + (1.000625)*SourceCoordinate

```

y coordinate follow the same procedure

# Answer
> 0 votes
Making a few assumptions:

* You are (eventually) interested in a matrix impementation, for convenience and power; and
* You are familiar with homogeneous coordinates.

Then the question migrates to: What is the homgeneous transformation matrix for my basis change?

To answer this we need the answers to three subsidiary quesions first:

1. Where did my origin move to?
2. What happened to my X-axis? Let (M11,M12) be the coordinates of the point
3. What happened to my Y-axis?

Define the answers to these thre questions to be as follows:

1. (M31,M32) are the coordinates of the new origin under the original coordinate system.
2. (M11,M12) are the coordinates of the new unit x-vector in the original coordinate system.
3. (M21,M22) are the coordinates of the new unit y-vector in the original coordinate system.

Then the homogenous transformation matrix is:

```
( M11, M12,  0 )
( M21, M22,  0 )
( M31, M32,  1 )

```

My convention here is that points are represented by row vectors, which is the normal computer graphics convention; the mathematicians and physicists often use the oppsoite.

---
Tags: 2d, coordinates
---


# Question
Title: Implementing a wrapping wire (like the Worms Ninja Rope) in a 2D physics engine
I've been trying out some rope-physics recently, and I've found that the "standard" solution - making a rope from a series of objects strung together with springs or joints - is unsatisfying. Especially when rope swinging is relevant to gameplay. I don't really care about a rope's ability to wrap up or sag (this can be faked for visuals anyway).

For gameplay, what is important is the ability for the rope to **wrap around the environment** and then subsequently unwrap. It doesn't even have to behave like rope - a "wire" made up of straight line segments would do. Here's an illustration:

This is very similar to the "Ninja Rope" from the game Worms.

Because I'm using a 2D physics engine - my environment is made up of 2D convex polygons. (Specifically I am using SAT in Farseer.)

So my question is this: **How would you implement the "wrapping" effect?**

It seems pretty obvious that the wire will be made up of a series of line segments that "split" and "join". And the final (active) segment of that line, where the moving object attaches, will be a fixed-length joint.

But what is the maths / algorithm involved for determining when and where the active line segment needs to be split? And when it needs to be joined with the previous segment?

(Previously this question also asked about doing this for a dynamic environment - I've decided to split that off into other questions.)

# Answer
To determine when to split the rope, you must look at the area that the rope covers each frame. What you do is you do a collision check with the area covered and your level geometry. The area that a swing covers should be an arc. If there is a collision, you need to make a new segment to the rope. Check for corners that collide with the swinging arc. If there are multiple corners that collide with the swing arc, you should pick the one where the angle between the rope during the previous frame and the collision point is the smallest.

The way you do the collision detection is that for the root of the current rope segment, O, the rope's end position on the previous frame, A, the rope's end position on the current frame, B, and each corner point P in a polygonal level geometry, you calculate (OA x OP), (OP x OB) and (OA x OB), where "x" represents taking the Z coordinate of the cross product between the two vectors. If all three results have the same sign, negative or positive, and the length of OP is smaller than the length of the rope segment, the point P is within the area covered by the swing, and you should split the rope. If you have multiple colliding corner points, you'll want to use the first one that hits the rope, meaning the one where the angle between OA and OP is the smallest. Use dot product to determine the angle.

As for joining segments, do a comparison between the previous segment and the arc of your current segment. If the current segment has swung from left side to the right side or vice versa, you should join the segments.

For the math for joining segments we'll use the attachment point of the previous rope segment, Q, as well as the ones we had for the splitting case. So now, you'll want to compare the vectors QO, OA and OB. If the sign of (QO x OA) is different from the sign of (QO x OB), the rope has crossed from left to right or vice versa, and you should join the segments. This of course can also happen if the rope swings 180 degrees, so if you want the rope to be able to wrap around a single point in space instead of a polygonal shape, you might want to add a special case for that.

This method of course does assume that you are doing collision detection for the object hanging from the rope, so that it doesn't end up inside the level geometry.
> 19 votes

# Answer
It's a while since I played Worms, but from what I remember - when the rope wraps around things, there's only one (straight) section of rope that's moving at any one time. The rest of the rope becomes static

So there's very little actual physics involved. The active section can be modelled as a single stiff spring with a mass on the end

The interesting bit will be the logic for splitting/joining inactive sections of the rope to/from the active section.

I'd imagine there'd be 2 main operations:

'Split' - The rope has intersected something. Split it at the intersection into an inactive section and the new, shorter, active section

'Join' - The active rope has moved into a position where the nearest intersection no longer exists (this may just be a simple angle/dot product test?). Rejoin 2 sections, creating a new, longer, active section

In a scene constructed from 2D polygons, all split points should be at a vertex on the collision mesh. Collision detection may simplify down to something along the lines of 'If the rope passes over a vertex on this update, split/join the rope at that vertex?
> 17 votes

# Answer
**Check out how the ninja rope in Gusanos was implemented:**

* The rope acts like a particle until it attaches to something.
* Once attached, the rope just applies a force onto the worm.
* Attaching to dynamic objects (like other worms) is still a TODO: in this code.
* I can't recall if wrapping around objects/corners is supported...

**Relevant excerpt from ninjarope.cpp:**

---

```
void NinjaRope::think()
{
    if ( m_length > game.options.ninja_rope_maxLength )
        m_length = game.options.ninja_rope_maxLength;

    if (!active)
        return;

    if ( justCreated && m_type->creation )
    {
        m_type->creation->run(this);
        justCreated = false;
    }

    for ( int i = 0; !deleteMe && i < m_type->repeat; ++i)
    {
        pos += spd;

        BaseVec<long> ipos(pos);

        // TODO: Try to attach to worms/objects

        Vec diff(m_worm->pos, pos);
        float curLen = diff.length();
        Vec force(diff * game.options.ninja_rope_pullForce);

        if(!game.level.getMaterial( ipos.x, ipos.y ).particle_pass)
        {
            if(!attached)
            {
                m_length = 450.f / 16.f - 1.0f;
                attached = true;
                spd.zero();
                if ( m_type->groundCollision  )
                    m_type->groundCollision->run(this);
            }
        }
        else
            attached = false;

        if(attached)
        {
            if(curLen > m_length)
            {
                m_worm->addSpeed(force / curLen);
            }
        }
        else
        {
            spd.y += m_type->gravity;

            if(curLen > m_length)
            {
                spd -= force / curLen;
            }
        }
    }
}

```
> 3 votes

# Answer
I'm afraid I can't give you a concrete algorithm off the top of my head, but it occurs to me that there are only two things that matter for detecting a collision for the ninja rope: any and all potentially colliding vertices on obstacles within a radius of the last "split" equal to the remaining length of the segment; and the current direction of swing (clockwise or counter clockwise). If you created a temporary list of angles from the "split" vertex to each of the nearby vertices, your algorithm would just need to care if your segment was about to swing past that angle for any given vertex. If it is, then you need to do a split operation, which is easy as pie -- It's just a line from the last split vertex to the new split, and then a new remainder is calculated.

I think only the vertices matter. If you're in danger of hitting a segment between vertices on an obstacle, then your normal collision detection for the guy hanging at the end of the rope should kick in. In other words, your rope is only ever going to "snag" on corners anyway, so the segments between won't matter.

Sorry I don't have anything concrete, but hopefully that gets you where you need to be, conceptually, to make this happen. :)
> 1 votes

# Answer
Here's a post which has links to papers about similar types of simulations (in engineering/academic contexts rather than for games): https://gamedev.stackexchange.com/a/10350/6398

I've tried at least two different approaches to collision detection+response for this sort of "wire" simulation (as seen in the game Umihara Kawase); at least, I think this is what you're after -- there doesn't seem to be a specific term for this sort of simulation, I just tend to call it "wire" rather than "rope" because it seems like most people consider "rope" to be synonymous with "a chain of particles". And, if you want the stick-ish behaviour of ninja rope (i.e it can push AND pull), this is sort of more like a rigid wire than a rope. Anyway..

Pekuja's answer is good, you can implement continuous collision detection by solving for the time when the signed area of the three points is 0.

(I can't fully recall OTOH but you can approach it as follows: find the time t when point a is contained in line passing through b,c, (I think I did this by solving for when dot(a-b,c-b) = 0 to find values of t), and then given a valid time 0\<=t\<1, find the parametric position s of a on the segment bc, i.e a = (1-s)*b + s*c and if a is between b and c (i.e if 0\<=s\<=1) it's a valid collision.

AFAICR you can approach it the other way around too (i.e solve for s and then plug this in to find t) but it's a lot less intuitive. (I'm sorry if this doesn't make any sense, I don't have time to dig up my notes and it's been a few years!))

So, you can now calculate all the times at which events happen (i.e rope nodes should be inserted or removed); process the earliest event (insert or remove a node) and then repeat/recurse until there are no more events between t=0 and t=1.

One warning about this approach: if the objects that the rope can wrap around are dynamic (especially if you're simulating them AND their effects on the rope, and vice-versa) then there can be problems if those objects clip/pass through each other -- the wire can become tangled. And it will definitely be challenging to prevent this sort of interaction/movement (the corners of objects slipping through each other) in a box2d-style physics simulation.. small amounts of penetration between objects is normal behaviour in that context.

(At least.. this was a problem with one of my implementations of "wire".)

A different solution, which is much more stable but which misses some collisions in certain conditions is to just use static tests (i.e don't worry about ordering by time, just recursively subdivide each segment in collision as you find them), which can be a lot more robust -- the wire won't tangle at corners and small amounts of penetration will be fine.

I think Pekuja's approach works for this too, however there are alternate approaches. One approach I've used is to add auxiliary collision data: at each convex vertex v in the world (i.e the corners of shapes which the rope can wrap around), add a point u forming the directed line segment uv, where u is some point "inside the corner" (i.e inside the world, "behind" v; to calculate u you can cast a ray inward from v along its interpolated normal and stop some distance after v or before the ray intersects with an edge of the world and exits the solid region. Or, you can just manually paint the segments into the world using a visual tool/level editor).

Anyway, you now have a set of "corner linesegs" uv; for each uv, and each segment ab in the wire, check if ab and uv intersect (i.e static, boolean lineseg-lineseg intersection query); if so, recurse (split the lineseg ab into av and vb, i.e insert v), recording which direction the rope bent at v. Then for each pair of neighbouring linesegs ab,bc in the wire, test if the current bend direction at b is the same as when b was generated (all of these "bend direction" tests are just signed-area tests); if not, merge the two segments into ac (i.e remove b).

Or maybe I merged and then split, I forget -- but it definitely works in at least one of the two possible orders! :)

Given all the wire segments calculated for the current frame, you can then simulate a distance constraint between the two wire endpoints (and you can even involve the interior points, i.e the contact points between the wire and the world, but that's a bit more involved).

Anyway, hopefully this will be of some use... the papers in the post I linked too should also give you some ideas.
> 1 votes

# Answer
One approach to this is to model the rope as collidable particles, connected by springs. (fairly stiff ones, possibly even just as a bone instead). The particles collide with the environment, making sure the rope wraps around items.

Here's a demo with source: http://www.ewjordan.com/rgbDemo/

(Move over to the right on the first level, there's a red rope you can interact with)
> 0 votes

---
Tags: farseer-physics-engine, physics, rope-physics
---


# Question
Title: What effect does the amount of 0 in a stat have.
Basically I want to know if the following three characters are the same

character A health 10 strength 3 defence 2

character B health 100 strength 30 defence 20

character C health 1000 strength 300 defence 200

In traditional RPG games health/mana ranges from 0-9999 and the other stats are 0-999, is this just a tradition or is there a mechanical reason for it?

What would be the pros and cons of using each character above as the base model if there are any differences. I am think is all aspects so what affect it will have on battle maths, player perception, game balance.

# Answer
> 1 votes
Generally speaking, this comes from a number of different factors, both technical and psychological.

For one, early RPGs had technical limitations imposed on them as to the number of differentiable values, especially in the era of 8-bit and 16-bit processors in game consoles. The maximum range of 8-bit integer values is 0-255, and for 16-bit integers, 0-65535. (In addition, I won't even go into how difficult it would have been on early platforms to represent decimal values.) This left a very limited range of relevant values for game designers to work with, so they (mostly) chose ranges which allowed decent levels of differentiation and gameplay balance, allowing for probabilistic and stat-based strategies to be created (think Pokemon's damage system), while still being within the ranges allowed by the processor.

In the above comment, the concept of aesthetically-pleasing numeric values is touched upon. These numbers are easy for us as humans to grasp, since they avoid what I like to call "zero shock" and "decimal/fraction shock". They are integers, which means we don't have to deal with differing scales or having to interpret decimals mentally, but they don't have an excess of wasteful information (extra zeros), which is not relevant to quantifying the importance of the value itself.

# Answer
> 1 votes
In addition to the other posts, consider how a larger health pool will allow you to better control stats at a finer level.

**Case 1:**

Max\_Health = 10, Min\_Damage = 1 (10% of max HP)

Therefore if your character receives the minimum amount of damage from an enemy, the highest health your character can have is 9, or 90% health.

**Case 2:**

Max\_Health = 100, Min\_Damage = 1 (1% of max HP)

Now the health pool is much larger and you can reduce (or increase, etc) the player's health to 99, or 99% health.

This also applies to the use of player attributes such as Strength, Intelligence, etc.

---
Tags: mathematics
---


# Question
Title: Complete Math Library for use in OpenGL ES 2.0 Game?
Are you aware of a **complete** (or almost complete) **cross platform math library** for use in OpenGL ES 2.0 games?

The library should contain:

* Matrix2x2, Matrix 3x3, Matrix4x4 classes
* Quaternions
* Vector2, Vector3, Vector4 Classes
* Euler Angle Class
* Operations amongh the above mentioned classes, conversions, etc..
* Standardly used math operations in 3D graphics (Dot Product, Cross Product, SLERP, etc...)

Is there such Math API available either **standalone** or as a **part of any package**?

*Programming Language: Visual C++ but planned to be ported to OS X and Android OS.*

# Answer
Have you considered the Configurable Math Library?
> 14 votes

# Answer
Eigen is a C++ header only math library that supports SSE, AltiVec and ARM Neon vectorisation.
> 8 votes

# Answer
Here are 2:

1. Sony's vectormath
2. Bullet's Linearmath
> 6 votes

# Answer
I worked on adding Apple's GLKMath to the this test *(actually forked this fork)*

Here's the result on my 4 Generation iPod Touch:

```
Eigen:
Additions: 77624 milliseconds.
Multiplications: 227179 milliseconds.

GLM:
Additions: 23935 milliseconds.
Multiplications: 80599 milliseconds.

CML:
Additions: 102390 milliseconds.
Multiplications: 161059 milliseconds.

GLKMath:
Additions: 8526 milliseconds.
Multiplications: 21775 milliseconds.

```

Here's my code

I don't have an Android Device, but I'm curious how GLKMath will perform on Android.
> 4 votes

# Answer
This is an old question, but I came across a very recent article that addresses just this issue by taking into consideration performance, documentation, ease-of-use, etc...

http://www.mfoot.com/blog/2012/01/23/choosing-a-maths-library-for-cross-platform-c-game-development/
> 3 votes

---
Tags: c++, mathematics, software-engineering, opengl-es, graphics-programming
---


# Question
Title: Latency difference between DirectSound and XAudio2
As far as I understand the WDM, DirectSound drivers cannot be hardware accelerated on Windows Vista and newer. Is XAudio2 affected as well?

Or in other terms: in *latency* terms is it definitely better to use XAudio2 instead of DirectSound?

I'm asking this because I want to go back to DirectSound for my next game to simplify deployment (XAudio2 requires a COM registration, which requires admin privileges and therefore an installer, and also causes trouble on emulated environments), but if there is a difference in latency, then I'll stay with XAudio2.

# Answer
> 1 votes
All you can do to be sure is testing, but I have never noticed audio latency in older games on Windows Vista and Windows 7. The biggest problem for non-hardware acceleration using the new audio path in Vista/7 is that EAX didn't work anymore (though some of that could be simulated through OpenAL). Of course XAudio2 has a lot of features that DirectSound doesn't have.

So bottom line, I don't expect problems, just make sure you have all the features in DirectSound that you are used to in XAudio2 and you should be good to go!

---
Tags: directx, xaudio2
---


# Question
Title: How do I check for non tilted 2D rectangle collision?
I'm trying to find out how to check collision with different rectangles. Now the cubes I have have a x, y, height, and width to them.

So it might look like this on the screen:

And not like this:

Now I want to detect collision and then determine what to do. This is where I'm stuck. I don't know how to detect if two rectangles are inside each other or not and how to determine which side can the object not move to. If anyone knows what algorithm to use here to determine these thing help is much appreciated.

# Answer
This sounds like you're looking for basic AABB bounding box collision, which is essentially rather trivial.

Essentially you've got two similar problems here (the same problem in two different dimensions):

**Determine whether two ranges overlap.**

Why? Simple: If the ranges in one dimension overlap, both rectangles are at least in some way on the same height (i.e. next to each other; even if that distance is a bit far). If the ranges in both dimensions overlap, your rectangles overlap as well (i.e. they collide).

Determining whether two ranges in one dimension overlap is a rather trivial problem:

* The right border of rectangle `a` must not be left of the left border of rectangle `b`.
* The right border of rectangle `b` must not be left of the left border of rectangle `a`.
* If both conditions are true, the ranges overlap.

Applying this to both dimensions is rather easy:

```
collide_x = a.x + a.w > b.x && b.x + b.w > a.x; // collide horizontally
collide_y = a.y + a.h > b.y && b.y + b.h > a.y; // collide vertically
collide = collide_x && collide_y; // collide in both dimensions

```

Or, unified to check everything within one line:

```
collide = a.x + a.w > b.x && b.x + b.w > a.x && a.y + a.h > b.y && b.y + b.h > a.y;

```

Once this is done, you can simply compare the x and y coordinates to determine in which direction the collision happens. You can also calculate how far these overlap by doing some more math with coordinates, e.g. using something like this:

```
distance_x = min(abs(a.x + a.w - b.x), abs(b.x + b.w - a.x));
distance_y = min(abs(a.y + a.h - b.y), abs(b.y + b.h - a.y));

```
> 2 votes

---
Tags: 2d, collision-detection, game-design, game-mechanics
---


# Question
Title: Physics Simulation - Pushing an object with user control
I'm working on a 2D game engine using C, SDL and OpenGL. Have worked out basic graphics, physics, and broad phase collision detection. I am trying to realistically simulate "pushing" objects around. I have gotten halfway there, but it doesn't feel right. I've implemented the impulse calculation found here to change linear and angular velocity. I want the blocks to have weight to them, and to slow the player down.

Consider this video. The leftmost block is player controlled. This is how my simulation feels right now.

Is there a relevant mathematical formula for this?

# Answer
> 2 votes
Looks perfectly fine to me (ignoring some jumping back/forth). To actually get the feeling of weight impulse isn't enough. You'll have to implement friction to slow things down based on their weight. Without friction you won't feel weight once an object is in motion (i.e. after applying an impulse).

---
Tags: physics, c
---


# Question
Title: How can I output multiple sprite sheets from a single .fla?
I have to produce out three sprite sheets of differing sizes. To do so, I have three different `.fla` source files.

Obviously maintaining three files takes more time than maintaining one; is there some way that I can use one `.fla` and produce three differently-sized sprite sheets?

# Answer
Use key frames to your advantage

Combine you `.fla` files into one `.fla` by putting each separate sprite sheet on a key frame, then copy those frames and scale them to get your extra sizes.

You will then have a sequence of all your sprite sheets and different sizes on your timeline. Make sure your stage is big enough for your largest sheet then export movie as a `.png` sequence.

You will have to crop the smaller sizes, but in the process you will be able to optimize and index the colours on the sheets which may save you some more memory.
> 2 votes

---
Tags: actionscript-3, spritesheet
---


title: Windows Phone XNA guarding storage data

text:
# Question
Title: Windows Phone XNA guarding storage data
For a typical windows phone game where storage files could contain high scores or in-game currency data, how does one go about protecting these files from user tampering?

# Answer
> 2 votes
Each Windows Phone application has a private storage area (called Isolated Storage) assigned to itself. This area cannot be accessed by any other apps so it is considered safe to save sensitive data here.

The typical user won't be able to access it either. There **are** ways to do it though (via tools), so I'd also **encrypt** all sensitive data before storage. Then again, encryption is a good idea when working with sensitive data no matter how closed the storage area is.

There's an article discussing the whole thing on Isolated Storage here: http://www.jeffblankenburg.com/2010/10/15/31-days-of-windows-phone-day-15-isolated-storage/

An encryption w/ C# .NET question was asked on StackOverflow a while back: https://stackoverflow.com/questions/202011/encrypt-decrypt-string-in-net

Just one more thing: since you're so worried that users might tamper with your data, I presume you're working on a game that has some sort of online syncing functionality. If that's the case, then your best bet would be to keep sensitive data on the device for as long as required only. `Save data, send data to server, get response, delete data depending on the response, repeat when required.` Encrypting the data won't make it hack-proof.

If this is not your case, then you should not worry about the user tampering with the data. It's like protecting a single player game against cheats or hacks: not worth it.

---
Tags: xna, windows-phone-7, security
---


title: Spawning enemies at way points

text:
# Question
Title: Spawning enemies at way points
I'm trying to have my game spawn enemies when ever the player reaches a way point.

Right now, I have this functionality working. When my player gets to the first way, the enemies spawn. He only moves on once he has killed all of the enemies on the screen are dead. However, when he gets to the second way point, no enemies spawn.

Right now, in my collision class I call the following line of code:

```
Destroy(gameObject)

```

Whilst this work for the first way point, the second one wont spawn anything as the game object my collision class has been attached to has been destroyed. However, all of my enemies are prefabs and I thought the destroy function would only destroy that instance of the prefab. No matter when you called the instantiate method, it would only destroy that instance.

I'm spawning my enemies with the following method:

```
  public GameObject SpawnEnemies()
{
    Vector3 _position = new Vector3(transform.position.x, transform.position.y, transform.position.z);

    // instantiate particel system
    Instantiate(_particle, _position, Quaternion.identity);

    _clone = (GameObject)Instantiate(_enemy, _position, transform.rotation);
    _ai = _clone.GetComponent<HV_BaseAI>();
    _ai._waypoints = _wayPoints;

    return _clone;
}

```

Then I'm finding out how many of the enemies are still alive with the following code in my collision method:

```
  GameObject g, f; // enemies I want to spawn
    g = GameObject.FindGameObjectWithTag("SectionController");
    f = GameObject.FindGameObjectWithTag("SectionController");

    HV_SectionController tempSectionControllerGroundEnemies, tempSectionControllerFlyingEnemies;
    tempSectionControllerGroundEnemies = g.GetComponent<HV_SectionController>();
    tempSectionControllerFlyingEnemies = f.GetComponent<HV_SectionController>();

    tempSectionControllerGroundEnemies._numberOfGroundEnemies.Remove(gameObject); // remove enemies from list
    tempSectionControllerFlyingEnemies._numberOfFlyingEnemies.Remove(gameObject);
    //Destroy(gameObject);

    _numberOfGroundEnemies = tempSectionControllerGroundEnemies._numberOfGroundEnemies.Count;
    _numberOfFlyingEnemies = tempSectionControllerFlyingEnemies._numberOfFlyingEnemies.Count;

```

Then when I want to move on I do the following check:

```
 if (_groundEnemiesRemaining == 0)
        {
            MoveToNextSection();
            _sectionStartTime = Time.time;
        }

```

i know the above line is checking only one type of enemy at the moment, but its the ground enemies I'm having issues with at the moment.

Does anyone know how I can delete the enemy prefab I'm spawning from my first section, once they've been hit, then have it respawn at the next section without the error:

> The object of type 'GameObject' has been destroyed but you are still trying to access it.

# Answer
If you `destroy` your `gameObject` you need to re-instantiate it at some point. If you access something that's been destroyed, you'll get the access error you're seeing.

You don't show how or when you're first instantiating `gameObject`. I see you're using static references to `GameObject`, and setting `g` and `f` to instances of a `GameObject`, but never `gameObject`.

You can either just destroy the reference, or you can implement a `disable` functionality that just puts the instance to sleep (removing it from the world), where it can be reused in a future spawner.
> 1 votes

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