# Question
Title: how to keep display tick rate steady when using continuous collision detection?
(I've just found about this forum). I hope it is ok to repost my question again here. I posted this question at stackoverflow, but it looks like I might get better help here.

Here is the question:

I've implemented basic particles motion simulation with continuous collision detection.

But there is small issue in display.

Assume simple case of circles moving inside square. All elastic collisions. no firction. All motion is constant speed. No forces are involved, no gravity. So when a particle is moving, it is always moving at constant speed (in between collisions)

What I do now is this:

Let the simulation time step be 1 second (for example). This is the time step simulation is advanced before displaying the new state (unless there is a collision sooner than this).

At start of each time step, time for the next collision between any particles or a particle with a wall is determined. Call this the TOC time; let’s say TOC was .5 seconds in this case.

Since TOC is smaller than the standard time step, then the system is moved by TOC and the new system is displayed so that the new display shows any collisions as just taking place (say 2 circles just touched each other’s, or a circle just touched a wall)

Next, the collision(s) are resolved (i.e. speeds updated, changed directions etc..).

A new step is started. The same thing happens. Now assume there is no collision detected within the next 1 second (those 2 circles above will not be in collision any more, even though they are still touching, due to their speeds showing they are moving apart now), Hence, simulation time is advanced now by the full one second, the standard time step, and particles are moved on the screen using 1 second simulation time and new display is shown.

You see what has just happened: One frame ran for .5 seconds, but the next frame runs for 1 second, may be the 3rd frame is displayed after 2 seconds, may be the 4th frame is displayed after 2.8 seconds (because TOC was .8 seconds then) and so on.

What happens is that the motion of a particle on the screen appears to speed up or slow down, even though it is moving at constant speed and was not even involved in a collision.

i.e. Looking at one particle on its own, I see it suddenly speeding up or slowing down, becuase another particle had hit a wall.

This is because the display tick is not uniform. i.e. the frame rate update is changing, giving the false illusion that a particle is moving at non-constant speed while in fact it is moving at constant speed. The motion on the screen is not smooth, since the screen is not updating at constant rate.

I am not able to figure how to fix this. If I want to show 2 particles at the moment of the collision, I must draw the screen at different times. Drawing the screen always at the same tick interval, results in seeing 2 particles before the collision, and then after the collision, and not just when they colliding, which looked bad when I tried it.

So, how do real games handle this issue? How to display things in order to show collisions when it happen, yet keep the display tick constant? These 2 requirements seem to contradict each other’s.

# Answer
> 4 votes
Solution 1: You could work around that problem by rendering a trail of your particles. That will leave the impression they hit a wall or each other without needing to draw the frame in which the impact occurred and slowing down.

Solution 2: You would need to cleverly and subtly adjust particle speed so they only collide in discrete frames "rendering time" and not in x.5 or x.8 times like they do now.

The second thing I would suggest is to use an existing physics engine.

That problem never seems to be crucial when I use Box2D unless speeds are too high.

In which case I adjust speeds to prevent unattractive visuals like you mentioned.

You already know when the balls are going to collide, not introduce a tiny slowdown or speedup so they only collide on discrete frames and not in-between two frames.

I suggest a mix of both techniques. When you can adjust speed slightly, do that and always leave a blurry trail to leave the user with the impression that a hit occurred.

To **predict** a future collision and and slightly adjust speed in advance:

You can predict a future collision by testing each pair of particles like this:

Variables:

```
`v1 = the velocity of the first particle.`
`p1 = the position of the first particle`

`v2 = the velocity of the second particle.`
`p2 = the position of the second particle`

```
1. Sum up the speed of both particles : `u = v1 + v2` (u is the some of their velocites)
2. Draw a line through one of the particles with the same angle as the velocity. `a = u.y / u.y` ; `b = p1.y - a * p1.x` ; The line is : `y = ax + b`;
3. Now use geometry to find the closest point on the line to p2.
4. If the distance in that point is greater than the some of their radiuses, predict no collision. Else move to step 5.
5. Check for the points where the distance between them is exactly the sum of their radiuses and use the nearest one as their point of collision.
6. Calculate how many frames it will take for them to collide by measuring the distance between p1 and the point you found on the line.
7. Lets say it takes 8.6 frames, you can now give them each a fake speed of `v * 8.6/9` and they will collide in 9 frames. You can also slow them down(decelerate) them gradually so that it looks more natural. You would need to slow them down to a speed that averages with the current speed at `v * 8.6/9`.

Disadvantages in using this prediction system:

Complexity: `O(n^2)` so it should be used with a small number of particles.

Changing the particles speed may 'create new collisions' that would not have happened in the original speed. So it should only be used with sparse particle clouds.

# Answer
> 2 votes
There is two options, depending on your physics engine:

## 1. Your physics engine can handle variable timestep

In this case, take the time since last update and feed it into the physics engine. Should the simulation end early due to collisions you subtract this time with the time the simulation actually ran for, and then repeat the simulation until you get to a small enough time remaining.

```
timeRemaining = timeSinceLastFrame
while (timeRemaining > 0)
  timeReamining = timeRemaining - PhysicsUpdate(timeRemaining)

```

Depending on how well the physics engine can handle very small timesteps you might need to check for the remaining time being larger than (say) 0.1 seconds instead of 0 seconds. If you do this you might want to combine this answer with the next to make sure you don't drop fractions of a second all the time and thus run the simulation slower than normal speed:

## 2. Your physics engine cannot handle variable timesteps

While unlikely to be the case, since you already stated it can handle stopping early, to be complete I wanted to discuss this case.

In this case you want to minimize the difference between the actual simulation time, to the time taken per frame. To do this you keep track of the real time taken to reach this point, and subtract the simulated time from this each time you update.

```
realTime = realTime + timeSinceLastFrame
while (realTime > physicsEngineTimeStep)
  realTime = realTime - PhysicsUpdate()

```

In this case, real time should be kept between the update calls, so if you get 0.5 second update due to ending early you would keep 0.5 for the next frame. Should the next frame run in 0.5 or less it will then do another update right away to catch up to real time. This would still produce some small changes in observed speeds, but since you keep correcting it will average out, the smaller the time step the less noticeable it will be (at the cost of taking longer to simulate no doubt).

You can also run a frame if the real time passed is larger than, say, 75% of a timestep, this allows the simulation to run ahead of actual time (leaving realTime as a negative value for the next frame) but it also allows it to catch up to real time before it falls behind with a full time step (one second in your example). This would reduce the slowdowns and make them somewhat less noticeable.

```
while (realTime > physicsEngineTimeStep * 0.75)

```

As mentioned in 1. above, you can combine both answers into one:

```
realTime = realTime + timeSinceLastFrame
while (realTime > physicsEngineMinimumTimeStep)
  realTime = realTime - PhysicsUpdate(realTime)

```

---
Tags: collision-detection
---


# Question
Title: Making an efficient collision detection system
I'm very new to game development (just started 3 months ago) and I'm learning through creating a game engine. It's located here. In terms of collision, I know only brute-force detection, in which case, the game slows down if there are a number of objects. So my question is **How should I program the collisions?**

I want them to happen automatically for every object and call the object's `collision(GObject other)` method on each collision.

Are there any new algorithms which can make this fast? If so, can anybody shed some light on this topic?

# Answer
> 10 votes
I have seen your game samples. In this specific case I would use a grid. Divide the game screen into squares. Create a 2D-Array representing the game screen squares and containing reference to the game objects inside each square (2d array of object lists).

Check for collisions between all the objects that are inside the same squares (that can collide with one another). An average sized object can be in up to four squares at most.

Update the 2d-array every time you move an object. The object 'remembers' in which squares it is, so you only need to update 8 squares at most even if the object teleports away.

It is one of the best solutions as far as average running time goes because you only need to update once per-object and in most cases, you only need to check for collision once or less per-object. For instance in the space shooter, you would only be checking spaceships that are in the same square with a bullet.

---
Tags: java, collision-detection
---


# Question
Title: Can't use SFML sprite drawing and OpenGL rendering at the same time
I'm using some SFML built in functions to draw sprites and text as an overlay on top of some OpenGL rending in an SFML RenderWindow. The opengl rendering appears fine until I add the code to draw the sprites or text. The sprite or text drawing causes the OpenGL stuff to disappear.

The follow code show what I'm trying to do

```
sf::RenderWindow window(sf::VideoMode(viewport.width,viewport.height,32), "SFML Window");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

glOrtho(0,viewport.width,0,viewport.height,0,1);

while (window.pollEvent(Event))
    {
    //event handling...

    //begin drawing
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
    glColor3f(col.x,col.y,col.z);
    for(int i=0;i<3;i++)
        glVertex2f(pos.x+verts[i].x,pos.y+verts[i].y);
    glEnd();

    // adding this line causes all the  previous opengl triangles not to appear
    window.draw("Sometext");

    window.display();
}

```

# Answer
> 2 votes
Whats happening is that SFML also uses OpenGL to draw the text (or sprites) in 2D. So drawing of the text by SFML usually messes up whatever OpenGL state that you are using for you own OpenGL drawing.

SFML RenderWindow provides a pair of methods which allow you to 'save' the current OpenGL state onto a stack and restore the saved state from the stack. Just wrap the SFML drawing code with window.pushGLStates(); and window.popGLStates(); as in the code below.

```
sf::RenderWindow window(sf::VideoMode(viewport.width,viewport.height,32), "SFML Window");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

glOrtho(0,viewport.width,0,viewport.height,0,1);

while (window.pollEvent(Event))
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
    glColor3f(col.x,col.y,col.z);
    for(int i=0;i<3;i++)
        glVertex2f(pos.x+verts[i].x,pos.y+verts[i].y);
    glEnd();

    window.pushGLStates(); //save the current OpenGL state
    window.draw("Sometext");

    window.popGLStates(); //restore the saved OpenGL state to the way it was before we drew the text

    window.display();
}

```

---
Tags: opengl, sfml
---


title: Rendering projectiles

text:
# Question
Title: Rendering projectiles
I'm working on a simple game that has the user control a space ship that shoots small circular projectiles. However, I'm not sure how to render these. Right now I know how to make a `LPDIREC3DSURFACE` for a sprite and render it onto a `LPDIRECT3DDEVICE9`, but that's only for a single sprite. I assume I don't need to constantly create new surfaces and devices.
How should projectile generation/rendering be handled?
Thanks in advance.

# Answer
> 1 votes
You seem to be beginning with game development. For beginners I would always suggest starting with a game engine. Once you have few simple games under your belt, you will have much better idea about how 'expensive' certain operations are etc. and you can give a go at your own engine if you wish.

There are many way of rendering objects. But your question is flawed. You should be asking how do I render things with acceptable speed. Once you get to several hundred objects, unless you have properly setup your rendering pipeline, you will quickly hit performance bottleneck. The idea behind performance is to queue as many operations as possible and then hand them over to the GPU for rendering. So for practice, it does not matter what you render, chose your projectiles for example, but then setup a test where you render 5000 of them, and make sure you can get a good framerate (60fps minimum). Unless you can hit this milestone, there is no point coding other stuff. Once this works, then instead of rendering 5000 identical images, use the same principle but render what you want.

Once again, you see how this is getting complicated quickly. I suggest you use a game engine like Orge, Allegro etc.

---
Tags: c++, directx, rendering
---


# Question
Title: How to use Pixel Bender (pbj) in ActionScript3 on large Vectors to make fast calculations?
Remember my old question: 2d game view camera zoom, rotation & offset using 'Filter' / 'Shader' processing?

I figured I could use a Pixel Bender Shader to do the computation for any large group of elements in a game to save on processing time. At least it's a theory worth checking.

I also read this question: Pass large array to pixel shader

Which I'm guessing is about accomplishing the same thing in a different language.

I read this tutorial: http://unitzeroone.com/blog/2009/03/18/flash-10-massive-amounts-of-3d-particles-with-alchemy-source-included/

I am attempting to do some tests. Here is some of the code:

```
        private const SIZE : int = Math.pow(10, 5);
        private var testVectorNum : Vector.<Number>;

        private function testShader():void
        {
            shader.data.ab.value = [1.0, 8.0];
            shader.data.src.input = testVectorNum;

            shader.data.src.width = SIZE/400;
            shader.data.src.height = 100;
            shaderJob = new ShaderJob(shader, testVectorNum, SIZE / 4, 1);
            var time : int = getTimer(), i : int = 0;
            shaderJob.start(true);
            trace("TEST1 : ", getTimer() - time);
        }

```

The problem is that I keep getting a error saying:

`[Fault] exception, information=Error: Error #1000: The system is out of memory.`

Update:

I managed to partially workaround the problem by converting the vector into bitmapData: (Using this technique I still get a speed boost of 3x using Pixel Bender)

```
    private function testShader():void
    {
        shader.data.ab.value = [1.0, 8.0];
        var time : int = getTimer(), i : int = 0;
        testBitmapData.setVector(testBitmapData.rect, testVectorInt);
        shader.data.src.input = testBitmapData;

        shaderJob = new ShaderJob(shader, testBitmapData);
        shaderJob.start(true);
        testVectorInt = testBitmapData.getVector(testBitmapData.rect);
        trace("TEST1 : ", getTimer() - time);
    }

```

# Answer
> 2 votes
I found a complete solution to this issue.

Please notice size is now 10,000,000

Here is the new code snippet:

```
        private const SIZE : int = Math.pow(10, 7);
        private var testVectorInt : Vector.<Number>; //gotta use Number (not int)
        private var testVectorInt2 : Vector.<Number>; //Need separate vectors for I & O

        private function testShader():void
        {
            shader.data.ab.value = [1.0, 8.0];
            var time : int = getTimer(), i : int = 0;
            shader.data.src.input = testVectorInt;//testBitmapData;
            shader.data.src.width = SIZE/4000;
            shader.data.src.height = 1000;
            shaderJob = new ShaderJob(shader, testVectorNum, SIZE / 4000, 1000);//(shader, testVectorInt2, SIZE/4, 1);
            shaderJob.start(true);
            trace("TEST1 : ", getTimer() - time);
        }
    }

```

You might be wondering what is the speed difference?

Processing the Numbers one by one in a loop took: 1956ms

Doing it in Pixel Bender took: 189ms

This results is true for Flash Player 10.3 on my pc

---
Tags: actionscript-3, fragment-shader, flashdevelop
---


title: canvas graphic output doesn't work

text:
# Question
Title: canvas graphic output doesn't work
at the moment i'm developing a 3D-Vector-Coordinates-to-2D-Canvas-Calculation.
the code is ready, the canvas too, but something doesn't work right...
You can find my code at www.philip-maerz.de/game/enginetest/engine.js

I've posted my question already on computerbase.de, but there nobody could help me...

Already now, thanks for your answers ;)

Greetings P.M.

# Answer
> 1 votes
This line is the problem:

```
 for(var i=0;i<numberpoints;i+2) {

```

Change the i+2 to i += 2 because it is currently running as an endless loop.

# Answer
> 0 votes
If I may recommend, PlayN is a very interesting game engine, in that it has direct support for both desktop and HTML. It is started by some Google people, and was actually used for porting Angry Birds to HTML. Check it out at https://code.google.com/p/playn/. They already have rendering to both Canvas and WebGL, all automatically done for you.

---
Tags: javascript, html5, html-canvas
---


# Question
Title: detect asset change while running in unity editor?
Is it possible to detect asset change while running in the unity editor. When I update my model, I see it change but the xml data associated with it does not change. So it would be nice to detect that and reload the xml data while running in the unity editor.

# Answer
Try OnPostprocessModel (on asset pipeline objects only; does not work on regular scripts) which should be called anytime a model is imported. There are similar hooks for textures and so on as well.

If that doesn't work, or if you want to monitor files that don't correspond to Unity assets, you can set up your own file monitor using FileSystemWatcher to check for any new, modified, or deleted files.
> 2 votes

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


# Question
Title: What is the best way to get into game development and learn how to program with graphics?
I'm a 16 year old learning C++. My friend and I have dreams of starting our own indie game company and we would, both, like to know how to get into game development.

One of our major questions is: How does one tie in graphics with programming (mainly C++)

Thanks in advance,

Tux

# Answer
> 2 votes
I would suggest looking around and using what you like. I'll list some libraries that are commonly used by game developers writing 2D games in C++. I'll try my best to sound unbiased.

**SDL** Low-level library (easiest to understand for beginners) with basic image-blitting.

**SFML** High-level library with networking, sound output, & complex shape/sprite actions.

**Haaf's Game Engine** High-level library with basic sprite actions & sound output (meant for beginners).

Since you're just starting, I'd suggest SDL. It's good for the first game or two. Once you're more comfortable with the language, you could try other things.

LazyFoo's tutorials are great SDL tutorials for people who are still learning C++.

---
Tags: c++, graphics, education
---


title: Geometry shader for multiple primitives

text:
# Question
Title: Geometry shader for multiple primitives
How can I create a geometry shader that can handle multiple primitives? For example when creating a geometry shader for triangles, I define a layout like so:

```
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;

```

But if I use this shader then lines or points won't show up. So adding:

```
layout(triangles) in;
layout(triangle_strip, max_vertices=3) out;
layout(lines) in;
layout(line_strip, max_vertices=2) out;

```

The shader will compile and run, but will only render lines (or whatever the last primitive defined is).

So how do I define a single geometry shader that will handle multiple types of primitives? Or is that not possible and I need to create multiple shader programs and change shader programs before drawing each type?

# Answer
I don't believe OpenGL supports geometry shaders which output multiple types of primitives. I'm actually surprised that your second code block compiled... Perhaps it just overwrote the configuration?

You will have to create multiple shaders and switch between them, at least for triangles/lines and points. There's actually a trick you can do with a fragment shader to receive triangles but render only lines by discarding fragments that fall too far inside the triangle according to barycentric coordinates. For the exact implementation of that, I'd refer you to the OpenGL Orange Book and its section on geometry shaders and drawing a wireframe (I'll come back and edit after I track down the exact chapter).

Happy coding!
> 7 votes

# Answer
It isn't possible to create a program with geometry shaders that handle multiple primitive types.

That being said, you don't have to do a whole lot of work to support multiple primitive types. Thanks to ARB\_separate\_shader\_objects, you no longer *have* to link all of your shader stages together. You can have one vertex-only program, one fragment-only program, and 2-3 geometry-only programs that you mix-and-match together. As long as they use compatible interfaces, you'll be fine.
> 3 votes

---
Tags: opengl, shaders, glsl, geometry-shader
---


title: Building View Matrix in Direct3D11

text:
# Question
Title: Building View Matrix in Direct3D11
Am I doing it right? I converted this.

```
m_ViewMatrix = XMMatrixLookAtLH(XMLoadFloat3(&m_Position), lookAtVector, upVector);

```

to this one.

```
XMVECTOR vz = XMVector3Normalize( lookAtVector - XMLoadFloat3(&m_Position) );
XMVECTOR vx = XMVector3Normalize( XMVector3Cross( upVector, vz ) );
XMVECTOR vy = XMVector3Cross( vz, vx );

m_ViewMatrix.r[0] = vx;
m_ViewMatrix.r[1] = vy;
m_ViewMatrix.r[2] = vz;
m_ViewMatrix.r[3] = XMLoadFloat3(&m_Position);

m_ViewMatrix.r[0].m128_f32[3] = 0.0f;
m_ViewMatrix.r[1].m128_f32[3] = 0.0f;
m_ViewMatrix.r[2].m128_f32[3] = 0.0f;
m_ViewMatrix.r[3].m128_f32[3] = 1.0f;

m_ViewMatrix = XMMatrixInverse( &XMMatrixDeterminant(m_ViewMatrix), m_ViewMatrix );

```

Everything looks fine when I run it. Another question is, I saw on this site(http://webglfactory.blogspot.com/2011/06/how-to-create-view-matrix.html) that he subtracted lookat from position in his vector vz. I tried it but gave me wrong view matrix. Can anyone check my code. I'm studying linear algebra right now. Sucks my course doesn't have one.

Thank you, Balls

# Answer
First, XMMatrixInverse() first parameter is annotated as output, so for **XNAMath** it should be:

```
XMVECTOR vDeterminant;
m_ViewMatrix = XMMatrixInverse( &vDeterminant, m_ViewMatrix );

```

or for **DirectxMath**:

```
m_ViewMatrix = XMMatrixInverse( nullptr, m_ViewMatrix );

```

Second, if you look at implementation of XMMatrixLookAtLH(), you will find something like this:

```
XMMATRIX XMMatrixLookAtLH( FXMVECTOR EyePosition, FXMVECTOR FocusPosition, FXMVECTOR UpDirection )
{
    XMVECTOR EyeDirection = XMVectorSubtract( FocusPosition, EyePosition );

    XMVECTOR R2 = XMVector3Normalize( EyeDirection );

    XMVECTOR R0 = XMVector3Cross( UpDirection, R2 );
    R0 = XMVector3Normalize( R0 );

    XMVECTOR R1 = XMVector3Cross( R2, R0 );

    XMVECTOR NegEyePosition = XMVectorNegate( EyePosition );

    XMVECTOR D0 = XMVector3Dot( R0, NegEyePosition );
    XMVECTOR D1 = XMVector3Dot( R1, NegEyePosition );
    XMVECTOR D2 = XMVector3Dot( R2, NegEyePosition );

    XMMATRIX M;
    M.r[0] = XMVectorSelect( D0, R0, g_XMSelect1110.v );
    M.r[1] = XMVectorSelect( D1, R1, g_XMSelect1110.v );
    M.r[2] = XMVectorSelect( D2, R2, g_XMSelect1110.v );
    M.r[3] = g_XMIdentityR3.v;

    M = XMMatrixTranspose( M );

    return M;
}

```

Your link refer to OpenGL matrix, but you are using DirectX functions, look at this for differences between them.

EDIT: Implementation is in `DirectXMathMatrix.inl` or `xnamathmatrix.inl`,you can find them in DirectX SDK, or Windows 8.0 SDK, or download it here.
> 2 votes

---
Tags: mathematics, matrix, directx11
---


# Question
Title: XNA texture stretching at extreme coordinates
I was toying around with infinitely scrolling 2D textures using the XNA framework and came across a rather strange observation.

Using the basic draw code:

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, SamplerState.PointWrap, null, null);
spriteBatch.Draw(texture, Vector2.Zero, sourceRect, Color.White, 0.0f, Vector2.Zero, 2.0f, SpriteEffects.None, 1.0f);
spriteBatch.End();

```

with a small 32x32 texture and a sourceRect defined as:

```
sourceRect = new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height);

```

I was able to scroll the texture across the window infinitely by changing the X and Y coordinates of the sourceRect.

Playing with different coordinate locations, I noticed that if I made either of the coordinates too large, the texture no longer drew and was instead replaced by either a flat color or alternating bands of color. Tracing the coordinates back down, I found the following at around (0, -16,777,000):

As you can see, the texture in the top half of the image is stretched vertically.

My question is why is this occurring? Certainly I can do things like bind the x/y position to some low multiple of 32 to give the same effect without this occurring, so fixing it isn't an issue, but I'm curious about why this happens. My initial thought was perhaps it was overflowing the coordinate value or some such thing, but looking at a data type size chart, the next closest below is an unsigned short with a range of about 32,000, and above is an unsigned int with a range of around 2,000,000,000 so that isn't likely the cause.

**Update 1:** The image above shows the texture stretching vertically near (0, -16,777,000), and the texture stretches horizontally at around (-16,777,000, 0). If I go beyond this point on both axes, the texture is stretched in both directions. This occurs in both the positive and negative directions.

The above positions were noted with a 32x32 texture. With a 16x16 texture, the distortion occurs at the same location. Interestingly, with a 64x64 texture, the distortion occurs in the same location on the x-axis, but is actually farther on the y-axis, more near (0, -17,301,000). *It occurs at the same location with a 64x64 texture too, I mistakenly used a 64x66 texture before.*

**Update 2:** I have repeated the test with a 1024x1024 texture and have found the same results. I looked farther and noticed that it stretches again at double the distance, somewhere near (-33,554,000, -33,554,00), but then doesn't happen again until around 4 times the initial stretching point, near (-67,109,000, -67,109,000).

It seems to occur only at powers of two times that initial value, 16,777,216 * 2^n. The answer below by mh01 suggested to check the MaxTextureRepeat cap of my graphics card (a GeForce GTX 560). According to KluDX this cap has a value of 8192, and it's description indicates that texture coordinates are stored in 32-bit signed integers.

*Correction: The stretch points occur at 2^n intervals because my texture sizes are 2^n. Testing with a texture size of 25x33 resulted in the first stretch point appearing near (-13,107,000, -17,301,000). So while it's related to the texture's aspect ratio, it doesn't seem to be directly related to the texture's size.*

# Answer
Having been unable to come up with a better solution, I'm going to settle on this being due to floating point precision errors at such extreme coordinates. As Roy T. pointed out, you should never come across such coordinates in a properly set up environment, so it is effectively a non-issue, but hopefully this question will provide answers for those experiencing this issue.
> 0 votes

# Answer
I think you've found some weird corner case bug, but you should never be in the scenario that your source rect has a coordinate like -16.777,000. It looks like you're not 100% sure what source rect is for.

The source rectangle should 'never' (I'll get back to that) be larger than the size of the texture. What the source rectangle does is select the part of the texture that will be drawn to the sprite you've selected. Say you have a texture that is 200x200, now if you only want the top left quadrant to be drawn you would use a source rectangle like (0,0, 100, 100).

Now for infinitely scrolling textures. As you've noticed you can keep updating the x and y coordinates of the source rectangle to have it keep scrolling. This happens because in certain texture modes (like Linear Wrap) a coordinate that would be outside the texture is placed inside the texture again by using the modulo of the texture size. So to counter the bug you've encountered we need to add this code ourselves so that the linear wrap algorithm never encounters such large numbers.

So some code:

```
int x; //x-coordinate of source rectangle
int y; //y-coordinate of source rectangle
int width; //texture width
int height; //texture height

x = x % width; //x will always be smaller than 2x the texture width
y =y % height; //y will always be smaller than 2x the texture height

Rectangle sourceRect = new Rectangle(x,y, width, height);

```

This should fix your problem :)
> 2 votes

# Answer
Check the value for MaxTextureRepeat in your DirectX Caps Viewer (you'll need the DX SDK installed for this of course).
> 1 votes

---
Tags: xna, 2d, textures, coordinates
---


# Question
Title: OpenGL, objects disappear at a certain z distance
I'm writing a managed OpenGL library in C++, and I'm having a pretty annoying problem. Whenever I set an objects Z coordinate to -2.0 or lower, the object disappears. And at coordinates 0 through -1.9, it doesn't appear to move away from them camera. I have a world matrix (which is multiplied by the objects position to move it), a view matrix (which is just the identity matrix currently) and a projection matrix, which is setup like this:

* FOV: 45.0f
* Aspect Ratio: 1
* zNear: 0.1f
* zFar: 100.0f

using GLMs `glm::perspective` method. The order the matrices are multiplied by in the shader is world, view, projection, then position.

I can move the object along the X and Y axis perfectly fine. I have depth testing enabled, using `GL_LEQUAL`. I can change the actually vertices positions to anything I want, and they move away from the camera or towards it perfectly fine. It just seems to be the world matrix acting up. I'm using `glm::mat4` for the world matrix, and `glm::vec3` for positions. Whats going on here?

I'm also using OpenGL 3.1, GLSL version 140 (1.4?).

# Answer
As it turns out, the order I was multiplying my matrices in the shader was wrong. Originally, I had:

```
gl_Position = worldMatrix * viewMatrix * projectionMatrix * vec4(in_Position, 1.0);

```

But it works with:

```
gl_Position = projectionMatrix * viewMatrix * worldMatrix * vec4(in_Position, 1.0);

```

I always thought MVP was the order they were supposed to be multiplied in, not PVM. Maybe I'm doing something wrong, but as of now this works.
> 2 votes

# Answer
Okay, first off, I want to say that for your Projection's Aspect Ratio, you might want to divide the width by the height. (This will give you your aspect ratio, like 1920/1080 = 16:9 Ratio)

Anyway, where are you getting your model matrix? You're saying you're multiplying the world matrix by your objects position? I wanna say that could be a problem. (Although, this could just be me misunderstanding what you're saying)

All I can say is make sure your objects have their own matrices. That would basically be their World Matrix. Also make sure you multiply your ModelViewProj Matrix with your vertex position in your Vertex Shader.
> 2 votes

---
Tags: opengl, 3d, matrix
---


# Question
Title: windows phone 7 apps marketplace paid to free
I have question about paid and free + ad-based apps/games in wp7 marketplace, can I publish my app as paid version initially and later(after a month or so) can i publish the same app/game as free + ad based version? Is there any such rule/policy in wp7 marketplace. I could not find proper answer on the net not lucky enough. And i hope this is not off topic question. - Thanks

# Answer
> 2 votes
Yes, you can do this. In the settings for your app you get to set the price and "Free" is one of the options.

Some things to consider before doing it:

* It may be better to have a free and a paid version available to increase visibility.
* When switching from paid to free, or vice-versa, you won't get put the the top of the new apps list.
* The new list may not be such a big concern given that there are hundreds of new apps a day meaning this list is of little value. Some people may however be regularly checking new apps in a particular category.

---
Tags: windows-phone-7, marketing
---


title: Fast, accurate 2d collision

text:
# Question
Title: Fast, accurate 2d collision
I'm working on a 2d topdown shooter, and now need to go beyond my basic rectangle bounding box collision system.

I have large levels with many different sprites, all of which are different shapes and sizes. The textures for the sprites are all square png files with transparent backgrounds, so I also need a way to only have a collision when the player walks into the coloured part of the texture, and not the transparent background.

I plan to handle collision as follows:

1. Check if any sprites are in range of the player
2. Do a rect bounding box collision test
3. Do an accurate collision (Where I need help)

I don't mind advanced techniques, as I want to get this right with all my requirements in mind, but I'm not sure how to approach this. What techniques or even libraries to try. I know that I will probably need to create and store some kind of shape that accurately represents each sprite minus the transparent background.

I've read that per pixel is slow, so given my large levels and number of objects I don't think that would be suitable. I've also looked at Box2d, but haven't been able to find much documentation, or any examples of how to get it up and running with SFML.

# Answer
1. Step one, create a grid and update it for every object that moves.
2. Only check for collisions between objects in the same squares.
3. Check if the bounding box of the objects intersects (their containing rectangle).
4. Check for pixel perfect collision using a low res version of the outline(see Game Physics).
5. Do a normal check of the outline tracing as described in Game Physics (Q 2)

Step 1:

Create a grid 2d array. Every object knows which squares it occupies by it's x,y position and it's width and height. If an object is moved away, it clears itself from the old square and updates the new square that it's occupying.

This only takes O(n) in total for n objects. For any specific object O(1).

Step 2:

Run all the checks for collisions between objects in the same squares. No need to run tests for collisions between objects in different squares. An object can occupy up to four squares if it is of average size. This means very few checks.

Step 3:

Check for intersection between the objects rectangles. If no intersection exists, stop.

Step 4:

Check for pixel perfect collisions between the outlines of the objects only inside the area of intersection. It should be fast enough. If not, create a low res 2d-boolean array and check it first, if you find collisions there, you would only need to check a small segment in the high res 2d-array saving you some precious time.

Please read this for concept on how to split your game world into a **grid** of squares:

Making an efficient collision detection system

Please read this for intuition on how to detect **pixel perfect** collisions.

Game physics / 2D Collision detection AS3

You can improve performance significantly:

1. Saving a low res (1 / 16) version of the outline to check against first.
2. Only checking in the area where the two rects intersect.
3. by dividing the outline roughly into segments, and only checking for collisions between segments first.

Please feel welcome to comment and I will elaborate.
> 18 votes

---
Tags: c++, 2d, collision-detection, sfml
---


title: Game programming and quantity of timers

text:
# Question
Title: Game programming and quantity of timers
I've made a simple 2D game engine using C# and DirectX and it's fully functional for the demo I made to test it. I have a Timer object that uses QueryPerformanceCounter and I don't know what's the better choice: use only one timer in the game loop to update everything in the game, or an independent timer in every object that needs one.

My worry is that when I try to implement threads, what will happen with timers? What happens with the sync?

# Answer
Original answer:

Why would you implement threads? Unless they are used to resolve a performance problem, they are a waste of time you can invest in your next game project. If the game is not processor heavy I am not sure threads are a valuable improvement. They mostly affect systems powerful enough to handle the game without threads in the first place.

To answer your question: I believe there is no advantage in using multiple timers. One timer saves on memory and processing time. As far as I know, one time can be used with multiple threads. That is an issue that could be resolved in another question if you encounter a problem with threads & timers.

Reply to Krom Stern:

Why threading is negligibly important in simple 2d games:

1. Implementing threads, like any programming task is time consuming. More so when it is dealt with for the first time as everything becomes simpler with experience.
2. Threads are not a valuable improvement for a simple 2d-game. Such a game should preform perfectly well on a single thread:
    1. Commander Keen was one of the first platformers I played on the PC. That was 21 years ago. It is not a simple 2d-game. According to Moore's law PCs have become approximately 1000 times faster since then. If it was possible to write a complex 2d- game back then that performs well without using threads, I do believe it is possible on a machine that is a 1000 times faster.
    2. In fact systems today are very forgiving to 'passable' and 'second-rate' 2d game code. Look at source from LD compos where developers only have 48 hours to make a complete new game with a framework of their choice. 3.Other examples of noteable 2d-games that performed well on old machines are: Command and Conquer and Warcraft from 1995. These are shining examples that your 20 year old PC can handle a complex 2d-game without threading.
3. This article about threading suggests it is mostly used to take advantage of multi-core systems and while older CPUs like my SU4100 exist that have multi-core, they are still more than powerful enough to support a well built 2d game without threading.
4. 2d-Games have matured 15 years ago. If you look at great 2d games like 'Castlevania: Symphony of the Night' you will see that technology did not greatly affect the quality of 2d games since 1997. It did completely revamp the looks of 3d games since Quake(1) which has little relevance here.
5. When I said high-end systems, I did mean modern systems in general. I corrected that now.

Why not use multiple timers?

1. Like I stated before which I think does not require any references: more objects mean more memory usage and more processing power. This should be obvious in most cases.
2. The op did not state a valid game reason for adding multiple timers. This suggests to me this decision may be based on reasons related to learning and practicing programming. This is a bad idea from game design perspective. When you are working on a game, you need to invest your time wisely. Games require a lot of work. If you happen to find a way to produce games quickly. Make more games! Instead of worrying about programming practices. Unless there is a serious problem you're facing with the current architecture, continue concentrating your effort on developing a great game. That is a difference between a game developer and a CS student.
3. OP also did not suggest a bottleneck exists in the game that will be resolved by threading. This also hints to the possibility that threading was not used to alleviate some game performance issues. If such issues existed, game code should be looked at as there aren't any good reasons a simple 2d-game should have performance issues on a modern machine.

I hope that helps clarify why I feel that threads are not necessary and why additional timers should not be the main point of interest in the development of a simple 2d game.
> 4 votes

# Answer
It is absolutely critical to use a single timer! If you query for time for every object, that means a scene will be filled with many objects whose position is calculated at different time. You need to think about a single frame as an image of all objects, all frozen at a particular moment in time.

For more advanced physics or action simulation, you might go to two timers, one timer that changes e.g. 10 times per second and all actions are calculated relative to this one. And a second timer that is actually not independent, but is interpolated from the first one, so that you can get several frames in between the two physics updates.

As for the threads, this is a completely different question. Threads are about dividing the work, and not having separate time. If you have 4 cores, one main thread calculates the new time, and then divides the objects into 4 groups and each thread can calculate changes to one group. Then they all inform the main thread they are done, and the main thread can render all the objects at once. Notice how this way, even though 4 threads worked, they all calculated changes at the same, fixed moment in time.
> 3 votes

# Answer
In a simple game I would use at least 2 timers (on 2 separate threads), one for the update loop and one for the rendering loop. If updating your entities takes a long time this won't affect the game's fps and you still can get at least 60 fps. Also, updates might not need to be processed 60 or more times per second, maybe only on user input.
> 0 votes

# Answer
> I don't know what's the better choice: use only one timer in the game loop to update everything in the game, or an independent timer in every object that needs one.

A single timer is a viable option in many cases, but while one-time-per-object might be a bit overkill, there are good reasons to have multiple timers and/or time sources.

In general, **you want one time source for each batch of things that should operate on the same timeline**. Typically you'll have all your game logic objects slaved to a single time source, but you might also have a few extra timers for rendering systems -- perhaps one for the primary in-game rendering and one for interface rendering.

The reason you'd want to do this is because it allows you to implement certain behaviors very easy by simply scaling your time sources relative to real time. For example, you can implement game logic pausing by forcing the per-frame delta time returned from that time source to be to zero, or you can implement a "slowdown" effect by scaling that delta time by some factor, such as 50%. If your object updates are correctly written to handle it, you can even rewind time this way.

If you do that you'll want to be using a different time source for things like your HUD render effects, otherwise they would slow down (or pause!) when the game logic did, which would likely render them unusable.

It is often useful to separate out the actual real-time clock from the presentation of the per-frame time deltas (the actual time source), allowing you to drive multiple time sources off any given clock to ensure you're using a single canonical "current time" and simply scaling its delta appropriately in each source. There are also reasons to use a separate clock entirely for things like physics, which tend to work better with fixed time steps.
> 0 votes

---
Tags: c#, directx, timer
---


title: 'Spring' physics

text:
# Question
Title: 'Spring' physics
I'm trying to put together a struct or a method of some sort that will allow me to check the relative position between two objects, and if they're too far apart, apply a force that will draw them closer to eachother. I've read that you can achieve this by creating a 'spring', what that might look like in code?

# Answer
None-physical way (not spring physics):

If I simply wanted an object to pull towards another object and stop there I would use this instead:

Define too far apart as a radius `r`, any object farther than that radius will be attracted to its partner.

```
R = r*r;

```

Lets say the attractor is `A` and the other object is `B`

1. Pick a small percentage representing your speed : s = 25%; `//adjust s as needed`
2. Divide the percentage by 100 : s /= 100.0 `// s = 0.25`
3. Use this method:

`A.attract(B)`

```
deltaT = (currentTime - lastFrameTime) / 1000.0;    //time in seconds since last frame
deltaX = A.x - B.x;
deltaY = A.y - B.y;

if(deltaX * deltaX + deltaY * deltaY > R)
{
    B.x += s * deltaX * deltaT;
    B.y += s * deltaY * deltaT;
}
//could use some refinement to make the slowdown more gradual.

```

This would attract an object to another without 'letting go' once it gets there.

---

To simulate **spring physics** in one direction, use this:

```
`F=-kx`

```

k is a coefficient and x is the distance between the objects.

F will determine the acceleration speed between object A(attractor) and object B(attracted).

Edit:

Like dreta mentioned, you could use `x` (distance) to help calculate the new speed:

```
// dividing by distance to normalize
B.newVel.x = B.oldVel + ((A.x - B.x) / distance) * F

B.newVel.x = B.oldVel + ((A.x - B.x) / distance) * distance * k

```

Which is basically : (I am taking deltaT, frame time in seconds into account)

```
B.vel.x += (A.x - B.x) * k * deltaT; //You can divide by mass here
B.vel.y += (A.y - B.y) * k * deltaT; //Or adjust k to take that into account

```

---

Otherwise do something like:

To simulate the foce, check for the angle between them:

```
angle = Math.atan2(A.y - B.y, A.x - B.x);

```

The new velocity for B will be:

```
//We do not consider mass (assuming it is 1)
B.newVel.x = Math.cos(angle) * B.oldVel.x + F * delta;
B.newVel.y = Math.sin(angle) * B.oldVel.y + F * delta;

```

This is not classic spring behavior as it does not consider the fact that the spring will repel an object if it is too close (closer than the equilibrium point).

If you wish to emulate that, detract a constant `e` from the distance `x` and it will push the object away if it is too near. To make the object stop, you will need to weaken the spring, otherwise it will continue to move near and then away after reaching it's attractor.
> 6 votes

# Answer
What you need to implement is Hookes law. This is an equation which calculates the force created by a spring. The equation is;

F=-kx

where x is the how far a way the spring is from its 'natural' or resting length. i.e if a spring has a resting length of 5 meters and is stretched to 8 meters, x is 3 in this case. k is the spring constant, which controls how 'strong' the spring is. Note there is a minus sign. That is because the force acts in the opposite direction of the direction of stretching (or compression).

Once you know F, you can calculate the acceleration a=F/mass.

you will probably want to include damping in your model, otherwise an will bounce back and forth forever.

Now your equation will be

F=-kx-cv

v is the velocity of the object and c is the amount of damping (bigger values mean the oscillation will stop sooner
> 4 votes

# Answer
Rather than invoking physics, simpler solution would be to constantly adjust their positions to make sure that they are the required distance apart.

```
Vector2 disp=b.pos-a.pos; //displacement between both points

float adj=disp.length()-requiredLength; // how far are we from correct seperation

disp.normalize();

a.pos+=disp*0.01f*adj; //move a towards/away from b by 1% of the discrepancy
b.pos-=disp*0.01f*adj; //move b towards/away from a

```

In this code adjust the 0.01 value to make the objects move quicker or slower.
> 2 votes

---
Tags: xna, 2d, xna-4.0, physics
---


# Question
Title: How to setup Cocos2D-X (Android) under Mac OS X?
Hi I've made a small game for iPhone that I also want to run on Android but I'm having problems setting up Cocos2D-X for Android.

I've downloaded and installed Android SDK and NDK (under my `"/Users/username/Android"`).

Installed all necessary packages under SDK and created an Emulator. Copied Cocos2D-x under `"/Users/username/cocos2dx"`.

Installed Eclipse IDE with ADT Plugin.

Opened `"Users/username/cocos2dx/tests/build_native.sh"` and changed `"NDK_ROOT_LOCAL=/Users/username/Android/android-ndk"`, `"COCOS2DX_ROOT_LOCAL=/Users/username/cocos2dx"` to the values shown.

On running the script using Terminal it compiles test project. What's next?

# Answer
> 2 votes
The steps are as follows:

* Generate the project for Android using cocos2d-x template
* Add project to NVPack's Eclipse
* Fix make files, IDE configuration and whatnots
* Compile the libraries with Cygwin and build\_native.sh script, they will be automatically added to the obj folder of the project
* Execute/debug like an Android application

Those are the windows steps, I am not sure about the iOs part but it shouldn't be much different.

# Answer
> 1 votes
Here's a tutorial on creating a Cocos2d-X meta-project for multiple platforms.

---
Tags: c++, cocos2d-x
---


# Question
Title: How can I write data to a file that users can't easily edit?
> **Possible Duplicate:**
> How can I protect my save data from casual hacking?

While working on game saving and loading I figured I could just write all the variable values to a file and then load that file from it's default location anytime.

However from the very beginning it sounded like an odd job. I know about serialization and boost, but that seems so complicated, I figured I'd keep it simple, but I've ran across this huge issue: No matter what file I can write with C++, the user can get their hands on it, they can edit their position, they can remove a boss, or add new weapons for themselves.

My question here is: How can I create a file in C++ which cannot be editted or openned with a text editor such as Notepad (I'm not trying to make a file which is impossible to open, but a file which will give the user a headache if he tries to edit it through usual methods.)

# Answer
> 11 votes
Encrypt it. It's really that simple. Since you're trying to discourage casual editing (rather than a dedicated hacker), the encryption algorithm could be fairly simple. There's no need for PGP or something. You could use ROT13. Or develop a substitution cypher of your own.

# Answer
> 5 votes
You can just use a binary format and write the data structure to the file itself. To verify you are opening a proper and uncorrupted file, add a "magic" string to the data structure and check the string each time it's loaded (this is just a simple way to do it). An example of how to do this can be found here. Encryption can also be added with little hassle.

# Answer
> 3 votes
One last solution that I didn't see in other's answers is to add check some to your save data. For example you can calculate sum of all characters in your save file (excluding checksum) and print it at the end of file. this way if someone changes some characters in your file you can easily notice them. you can also spread checksum bytes over your save file to make them less noticeable. maybe if you are using MD5 checksum and you expect your save file to be 256 characters length, you can save checksum in bytes \[2,4,6,....,512\]

# Answer
> 2 votes
From the comments I'm guessing you are currently using plain text as your saving method. If you want a quick fix to make things less accessible to the average user, instead of saving your text as it is, edit each character to be `255 - charval` of what it currently is and then when reading the file switch it back.

You could also do this: `char = (char + 100)%256` for writing and char = (char + 156)%256 for reading.

If you want something more complex, please feel welcome to comment and I will suggest a stronger form of protection.

For example if you wish to continue using text you can randomize an Injective function that receives a character and returns another character. An injective function has an Inverse function, which you can then use to read the text.

To create an injective function randomly, simply shuffle an array of integers from 0 to 255 and use the value in the index i to represent 'i' in your files.

To create the inverse function, create another array and run over the array like this:

```
for(int i = 0; i <= 255; i++)
{
    B[A[i]] = i;
}

```

Where `A` is the original array and `B` is the new one.

You can save these arrays in your code.

While this is not impossible to crack, I suspect I would not bother trying. I imagine most gamers (99% +) would avoid trying to edit a file like this.

If you really want to go the extra mile, there are some encryption techniques like RSA that are not very complicated to implement.

# Answer
> -2 votes
A method I used was to save the file with the extention of .csx instead of .txt. It's visible, but a user can't readily figure out how to open it, unless they change the extension to .txt again.

---
Tags: c++, assets, savegame
---


title: Embedding Pygame to C++

text:
# Question
Title: Embedding Pygame to C++
If embedding Pygame to C++ to have a game be an executable, is there any extra process I would have to use in order to use Pygame functions when embedding into C++? As opposed to just writing embedding code in C++ for normal Python code?

To clear cut the question I want to know if it's the same process without having to call different functions.

EDIT: My question is if I have to call different functions in C++ when embedding Python code that uses Pygame modules. I am NOT using pygame2exe nor py2exe. I never even mentioned those. My question is solely about code embedding.

# Answer
> 2 votes
When you embed Python into C++, you just have to set up the code to call the Python functions in C++. The Python libraries that you use, such as Pygame, have no effect on the C++ binding code you need to use.

---
Tags: c++, python, pygame
---


title: Android 2D terrain scrolling

text:
# Question
Title: Android 2D terrain scrolling
I want to make infinite 2D terrain based on my algorithm.Then I want to move it along Y axis (to the left) This is how I did it :

```
public class Terrain {
Queue<Integer> _bottom;

Paint _paint;

Bitmap _texture;

Point _screen;

int _numberOfColumns = 100;
int _columnWidth = 20;

public Terrain(int screenWidth, int screenHeight, Bitmap texture)
{
    _bottom = new LinkedList<Integer>();

    _screen = new Point(screenWidth, screenHeight);

    _numberOfColumns = screenWidth / 6;
    _columnWidth = screenWidth / _numberOfColumns;

    for(int i=0;i<=_numberOfColumns;i++)
    {
        // Generate terrain point and put it into _bottom queue
    }

    _paint = new Paint();
    _paint.setStyle(Paint.Style.FILL);
    _paint.setShader(new BitmapShader(texture, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
}

public void update()
{
    _bottom.remove();
    // Algorithm calculates next point
    _bottom.add(nextPoint);
}

public void draw(Canvas canvas)
{
    Iterator<Integer> i = _bottom.iterator();
    int counter = 0;
    Path path = new Path();
    path.moveTo(0, _screen.y);
    while (i.hasNext())
    {
        path.lineTo(counter, _screen.y-i.next());
        counter += _columnWidth;
    }
    path.lineTo(_screen.x, _screen.y);
    path.lineTo(0, _screen.y);
    canvas.drawPath(path2, _paint);
}

```

}

The problem is that the game is too 'fast', so I tried with pausing thread with

```
Thread.sleep(50);

```

in run() method of my game thread but then it looks too torn.

Well, is there any way to slow down drawing of my terrain ?

# Answer
The problem is that your drawing is tightly tied to your updates, and vice versa. If the game is drawing at 1000 frames per second, then update() is called 1000 times per second, and your terrain is going to scroll by at 1000 tiles per second.

The solution to that problem is to use a timestep to increment your simulation. In this case, say you want your terrain to scroll by at 60 tiles per second. That means you must call update() once every 1/60th of a second, and no more.

You can achieve this by using a timer and a time accumulator. Every time through your main loop, check how long has elapsed since the last time the loop ran. Add that value (generally represented as a floating point number in units of one second) to the accumulator. If the accumulator is greater than or equal to 1/60, subtract 1/60 from the accumulator and call update().

I'm not familiar with the Android timer APIs, but the general pseudocode looks something like:

```
// initialize time
last_time = GetCurrentTime();
accumulator = 0;
update_speed = 1/60;

while (!quit) {
  // calculate elapsed time since last frame
  current_time = GetCurrentTime();
  elapsed = ConvertToSeconds(current_time - last_time);

  // store current time for the next frame
  last_time = current_time;

  // if the accumulator is full enough, update game and "drain" accumulator
  accumulator += elapsed;
  if (accumulator >= update_speed) {
    update();
    accumulator -= elapsed;
  }

  draw();
}

```

Of course, this is a very rough and basic way to go about this. Going forward, you'll want to separate the speed the terrain scrolls by from your update time. You might have a character you need to update at 60 frames per second to feel "smooth" while the terrain is moving by at 20 tiles/second still. You can do this by using a "speed" multiplier for your world scrolling, giving it a separate timer/offset/accumulator from the one in your main game loop.

So far as the choppiness you encounter when you slow the game down, that is because you are moving the world one whole tile at a time. You should smoothly scroll the world, which is going to happen at the pixel level (or possible sub-pixel level, depending on what look/feel you're going for).

You'll want to store an offset in your tile data structure. As the update() function runs, simply increase this offset by your desired speed. (e.g. you want the terrain to move at 20 tiles/second, but you want to keep update() running as 60 calls/second for physics and such, so you increment the offset by 20 * update\_speed).

You will need to generate one "extra" tile, because as the world moves to the left, you'll see a part of the left-most tile and a part of the right-most tile just coming into the screen.

When the offset reaches or exceeds 1.0, that is when you remove the old tile on the left, generate yet another new tile on the right, and decrement the offset. Something like:

```
offset += scroll_speed * update_speed;
if (offset >= 1.0) {
  offset -= 1.0;
  RemoveLeftTile();
  AddRightTile();
}

```

Going down the road, there's a lot more to do and learn with how to get nice smooth animations, accurate timing and timesteps, and so on, but this should be a good start given your current game development skill level. When you're ready to deal with more advanced problems in the world of game timers and updates, there are already many great articles here on GDSE to help you out. :)
> 4 votes

# Answer
You need to split the update and draw loop into 2 separate threads with timers, this way you can draw your terrain as fast as possible (like 60fps) and slow down the update loop to match your requirements.
> 1 votes

---
Tags: android
---


title: How Do Day Night Cycles Work?

text:
# Question
Title: How Do Day Night Cycles Work?
I know that this is a vage question, but how do day night cycles work in video games? How do I get started programming one? I have researched for a while, but the only thing I saw was "unity 3-d day night cycle". I need just a basic concept.

Edit: I mean how to make it appear visually. I'm sorry for not saying that first.

# Answer
> 10 votes
This will depend a lot on what you want to acomplish and the type of game you have.

You would have a 'game world' time that advances based on the cpu clock. Generally at a much faster pace so it can be seen. And you will need to take into account pausing, alt-tabbing and so on. You can also advance it manually such as when the player sleeps, uses some kind of fast travel system (a less simple one would be based on the distance travelled) or from mission to mission. More complex game time keeping systems might keep a record of the date and potentially even have their own calendar systems (Like the Elder Scrolls series). This could influence weather and so on.

You need to adjust your visuals based on the game time. This normally involves lighting and the sky. For a simple system, outside will normally have a light that represents the sun. You would need to adjust the brightness/color based on the time of the day and set it to a much darker color at night. And the sky texture itself will need to switch between day, night and dawn/dusk textures (preferably with some kind of smooth fade).

More advanced visual systems will track a path for the sun and moon across the sky. A simpler system many just put them at polar opposites to each other and have them go directly overhead, east to west.

In reality both bodies have their own paths. The moon can be up during the day at the same time the sun is. The moon has cycles. And both will often not be directly over head but on an arc the angle of which changes depending on the time of the year. The stars them selves will change slightly too.

Skyrim was even more advanced and had 3 moons. The original Theif games actually had star charts rather than just using a texture.

You will also want to use the suns position for shadows is you have realtime ones.

# Answer
> 8 votes
The reason you're not finding anything is probably because it's so exceedingly simple there's nothing to ask about and nothing much to talk about.

### Here's how a day/night cycle works:

* You have a sun and moon that travel overhead (maybe also stars, etc).
* Your game has a time of day.
* The position of the sun and moon, and appearance of the sky, depends on the time of day.
* The lighting conditions also depend on the time of day.
* There might be mechanics to let you skip a certain number of hours ahead: you can wait/rest until a given time of day in The Witcher 2, and Minecraft has beds which let you sleep til dawn.

That's it. That's all there is to it. Whatever else you want to do is up to you.

# Answer
> 3 votes
They work just like day/night cycles in real life. It's daylight for a specific amount of time, then it's dark for a specific amount of time.

Basically you have an elapsed time counter. You decide how much real world time converts to your game time day.

This is typically displayed through the skybox and lighting. Display a sun and blue sky during the day, show starts and the moon at night.

---
Tags: lwjgl
---


title: Adjust treble and bass on Audio in XNA

text:
# Question
Title: Adjust treble and bass on Audio in XNA
I am trying to "muffle" the sounds that are being played in my game and the best way I can think of doing this, is by lowering the treble of the sound.

I have looked through all the members of the `Song / SoundEffect / SoundEffectInstance` classes and I cannot find a way to alter the sounds.

How can I accomplish this?

# Answer
> 3 votes
With XNA you have two approaches: mix your own filters as Bjorn describes in his answer with `DynamicSoundEffectInstance` (it's fun, try it :) ). The other option is XACT Variables.

Watch this video to see somebody use XACT variables to dynamically change an engine sound over time using pitch. To accomplish what you want, do something similar, but use it to adjust the parameters of a low pass filter (XACT should have it built in).

You can adjust the variables via `Cue.SetVariable` and `Cue.GetVariable`. See the MSDN docs for more info. Unfortunately, Microsoft has retired XACT, so all the detailed documentation on the tool has disappeared. But there are still blog posts and videos like the one I linked that can show you how to get stuff done.

# Answer
> 3 votes
I don't know XNA, but I can give you a generic answer:

What you want is a "low-pass filter" which is a kind of EQ, or equalizer, sometimes simply called an "audio filter". If the system you are using does not have one, you can use a moving average filter: so each sample output will be the average of the previous N inputs (the bigger N is the more "muffling" you will get, but past three or four, you'll be doing a lot of work for not much return).

If the moving average filter isn't sufficient (and it probably isn't), the standard approach is the "digital biquad". I describe how to write your own in this blog entry:

http://blog.bjornroche.com/2012/08/basic-audio-eqs.html

(I describe a bell filter, but a low-pass is simpler.)

---
Tags: xna, c#, .net, audio
---


title: Basic/research RTS engine/model

text:
# Question
Title: Basic/research RTS engine/model
Does a basic/research RTS engine/model exist that can be used as a basis for further experimentation/research? I'd like to avoid reinventing the wheel if possible.
I'm aware of Spring Engine and Stratagus, but those are real game engines and may not be the best to experiment with and learn from.
Ideally the docs for the model would answer questions like:

* How exactly do units move? (constant velocity? constant acceleration? constant force?)
* How is pathfinding handled? Does every grid cell become an A\* graph node (may be expensive)? Does it consider threats?
* How are groups handled? (w.r.t pathfinding and movement)
* How is combat handled?

I'm mostly interested in the low-level model details (for now), not the graphics etc.
I've read a lot of the other quesions (and answers/references) tagged RTS but I haven't found my answer yet.

# Answer
You have several excellent options.

First, building your own such testbed in Unity3D is ridiculously easy. I won't comment on whether or not Unity3D is up to snuff to ship a commercial grade RTS, but it's definitely capable of building a prototype RTS with little fuss. If you're interested in actually building a custom RTS with very specific gameplay or controls, this is probably your best bet.

Second, there are FOSS (Free/Open Source Software) RTS game engines and even complete games. Examples include Spring RTS Engine, Wargus, 0 AD, and I'm sure at least a few more. Google will serve you well here. This option may well be your best if you're solely interested in tweaking certain algorithms and don't care about coding anything else.

Lastly, there are also FOSS engines that will give you close to the ease of use of something like Unity while giving you the freedom and control of a completely Open engine. Torque 3D recently went Open Source, for example, and at one time there used to be an RTS Starter Kit for it (doesn't seem to be around anymore, but the starter kits were basically "Genre for Dummies" in Torque). There are a small handful of other FOSS engines around as well that may work for you (most are just uninspired derivatives of the ancient idTech engines that have been GPL'd, though). I personally believe this route to be an inferior option to Unity, unless you're completely devoid of spare cash or if you are a strong advocate for FOSS and avoid proprietary software on ethical grounds.
> 3 votes

# Answer
This isn't a research engine thingy, and it might not be very practical, but you could probably roll out a Starcraft mod. It's *the* classic RTS so it could be a very good starting point for your experiments.
> 1 votes

# Answer
As far as an RTS is concerned, there is no need for anything but velocity. Velocity is a vector containing two components, a speed, and a direction. The speed will vary based on unit buffs and debuffs, and the direction of course depends on where the unit is told to go. As such unit movement should be a rather simple procedure.

The question of pathfinding has been answered at the following link \> How does pathfinding in RTS games work?
> -1 votes

---
Tags: rts
---


title: Debugging-Setting Consoles in Games

text:
# Question
Title: Debugging-Setting Consoles in Games
Right now I have the graphical and input portions of a console for my game (command parsing hasn't been implemented yet). I was wondering how you would go about making changes to properties in game objects. For example, if I typed in the console:

```
skeletonMonster maxHP 20

```

That would change all of the existing in-game skeletons' max hit points to 20. After you parse this information what are some ways to change the value? How can I change the that member variable without directly accessing it (by making it public/global)?

I'd like to implement this so I don't have to change variables in the code and recompile every time while playtesting.

# Answer
The broad answer to your question is that you need a metadata/reflection/introspection system of some kind. This is a way for your engine to expose properties on objects to external modules. These systems can be used for a great many things: file serialization, in-game GUI editors, network synchronization, script binding, and of course in-game consoles.

Depending on the language you're using, such a system can range from trivial (say, in C# that already has an excellent reflection system built into the .NET library) to mind-boggling painful (such as in C++, which lacks built-in reflection or any way to portability build a fully featured one).

If you expand your question with some more information on the language you're using, more direct answers would be possible. As is, the best we can do is point you towards those terms (**reflection** and **introspection** and **metadata**) to help you look through your language's documentation or to Google for guides on building custom reflection/metadata systems. (Though be warned you won't get much for C++. About all you'll find are projects like clReflect, which looks amazing though I've yet to give it a whirl, and some incomplete articles on my site.)

In general pseudocode for an object-oriented language, you might end up with some kind of "register" method on all your classes that create an index of member variables (and possibly even methods) that exist, along with metadata about how they are to be used and accessed. Even in languages that have a full reflection system, if they lack user-specific attributes, you may still want a custom metadata system in order to annotate members with additional information (like whether they should be readonly, or what their min/max values are, etc.). In C++, you can also bind getters and setters rather than only directly member variable access, which can be advantages; again, though, it's a very non-trivial task and requires decent knowledge of template metaprogramming to pull off. In the general sense, this should get your wheels turning:

```
void MyClass.RegisterMeta(inout MetaData meta) {
  meta.AddROMemberVec3(MyClass.velocity, "Unit velocity")
  meta.AddRWMemberVec3(MyClass.position, "Unit position")
  meta.AddRWMemberInt(MyClass.health, "Remaining health", 0, C_MAX_HEALTH)
  meta.AddRWMemberInt(MyClass.maxHealth, "Maximum health", 0, C_MAX_HEALTH)
}

```

If you're looking to maximize on runtime flexibility and interation time, you might consider using a component based design approach to building game objects. You can also use a component based design approach to resource objects (like monster definitions references by your monster game object instances). The usual introductory text on that topic is Evolve Your Hierarchy. I also personally think it's easier to build a custom metadata system using component based design, since it already gets you into thinking about decoupling data and exposing object metadata to higher-level systems.

Lastly, if you are working in C/C++ and are looking for a quick but messy solution (but which works just fine for the vast majority of indie/hobby games), take a look at AntTweakBar. It's an in-game GUI system for building editors and property tweakers. It can be used for global game config, per-object properties, and so on. I know of more than a few fantastical games that have been released which used AntTweakBar as their sole game content editor GUI, and used a console only for debug output. The API is a little error prone and it's not super flexible or featured, but it gets the job done a heck of a better than any text-oriented console ever could. I would be surprised if there aren't similar tools (or bindings to this one) for other languages, too.
> 2 votes

# Answer
In some games that I've seen, the debug console is actually the Lua interpreter prompt. That way, anything you can call from script can be done from the console.
> 6 votes

# Answer
Depending on what language and framework you are using, there are a couple of options (theoretically all the options will work for all common languages and frameworks...).

My first suggestion would be to store the information you want to change outside of the program on disc, and loading that data into the runtime at the start of execution. That way you do not have to recompile to test out new values. This of course requires that you restart the game each time you want to try new values. Unless... you have something in your runtime that detects changes to this file and reloads it upon an update.

Another solution, like others have suggested, is evaluating the command as part of your runtime and directly setting the new values. As you said though, you'd rather not expose those variables as public, so I would have those classes contain their own handlers for changes to their data. Whatever system is receiving and controlling console input would re-route requests to the appropriate objects (class types).
> 0 votes

---
Tags: architecture
---


# Question
Title: Counting no.of bodies present in certain area in box2d?
I am stuck on it:how can i count or find the no.of bodies present in any area in as3?would be thankful if any guys help me out.....

# Answer
Create a fixture which has the exact size as the desired area, set the fixture's sensor property to true and check the number of collisions which include the sensor fixture.

You can find more about sensor fixtures in the official box2d documentation
> 1 votes

---
Tags: box2d
---


# Question
Title: how can i get rotation vector from matrix4x4 in xna?
i want to get rotation vector from matrix to realize some parent-children system for models.

```

 Matrix bonePos = link.Bone.Transform * World;
 Matrix m = Matrix.CreateTranslation(link.Offset)
       * Matrix.CreateScale(link.gameObj.Scale.X, link.gameObj.Scale.Y,
                 link.gameObj.Scale.Z)
       * Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(link.gameObj.Rotation.Y),
                 MathHelper.ToRadians(link.gameObj.Rotation.X),
                 MathHelper.ToRadians(link.gameObj.Rotation.Z))
//need rotation vector from bone matrix here (now it's global model rotation vector)
        * Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(Rotation.Y),
                  MathHelper.ToRadians(Rotation.X),
                  MathHelper.ToRadians(Rotation.Z))
         * Matrix.CreateTranslation(bonePos.Translation);
link.gameObj.World = m;

```

where : link - struct with children model settings, like position, rotation etc.
And link.Bone - Parent Bone

# Answer
> 2 votes
```
Matrix.Decompose

```

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.matrix.decompose.aspx

---
Tags: matrix, vector
---


# Question
Title: How do I identify mouse clicks versus mouse down in games?
What is the most common way of handling mouse clicks in games?

Given that all you have in way of detecting input from the mouse is whether a button is up or down.

I currently just rely on the mouse down being a click, but this simple approach limits me greatly in what I want to achieve. For example I have some code that should only be run once on a mouse click, but using mouse down as a mouse click can cause the code to run more then once depending on how long the button is held down for. So I need to do it on a click!

But what is the best way to handle a click? Is a click when the mouse goes from mouse up to down or from down to up or is it a click if the button was down for less then x frames/milliseconds and then if so, is it considered mouse down and a click if its down for x frames/milliseconds or a click then mouse down?

I can see that each of the approaches can have their uses but which is the most common in games? And maybe i'll ask more specifically which is the most common in RTS games?

# Answer
You're on the right track with figuring out when the mouse is transitioning from down to up and writing a handler for that. For a lot of games, it's good enough to treat a mouseUp event as a click.

Depending on your game, you're probably want to handle both events -- for example, in an RTS, you'll probably want to incorporate drag-box selecting as well as single-click selecting. The difference is in determining how long the mouse was in the Down state before it's released.

(Yes, you basically answered your own question)
> 12 votes

# Answer
There is no 'best' - you need all of them.

If I'm firing a gun, I don't want to wait for the mouse to be released to trigger the weapon firing effect. And if you're dragging a box around a bunch of units, you start the drag action on mouse-down.

On the other hand, if I'm clicking a GUI item then I want to wait for the full click because that's what I'm used to.

So, you should probably implement mouse down, mouse up, mouse drag (mouse up in significantly different place to mouse down) and and mouse click (mouse up in same place as mouse down), and hook them up to parts of your game as you see fit.
> 4 votes

# Answer
Mouse buttons and keyboard keys can have a number of different events, what is available depends on your choice of language/library, most common:

Key down, triggers when a button is pressed.
Key up, triggers when a button is released.
Retarded key down, triggers when a button is pressed, and then fires repeatedly at some system dependent interval until the key is released.

On top of this there may also be a call to tell whether or not a key is currently held down.

It is important that you are aware exactly what tool you are using, most commonly you will need the two first, if they are not available, build them from whatever is available.

Standard method for registering that an on-screen button is pressed using the mouse is to assert that the same button was pointed at both at the down and the up event. For many game elements this may however be too slow, so for a lot of actions it may be prudent to make them happen at the down event.
> 1 votes

# Answer
The way most windowing systems handle it, as well as the games that I've worked on (and had to partially implement myself) is to have a bit on each button that detects if the mouse entered the mouse down state over the given button. It is only set the frame that the mouse goes down and only cleared when the mouse button is released. If and only if the mouse is released over the button and the bit is set, then fire off the button clicked event.

(You probably also want a flag that is set true when the bit is set and the mouse is hovering over your button, so that you can change the button to use a pressed texture instead of it's normal one.)

This is the basic scheme behind most buttons. Go ahead and find a dialog prompt. Press down on the cancel button but do not let go. The button becomes depressed while the mouse is over it, and goes back to normal if your mouse stops hovering over it, but it will go back to pressed if you move back over it. It only runs its action if you let go and you're over it. Do not use a millisecond count, that's mostly just for detecting double clicks within your threshold.

(and if you really want to get fancy, have events that you can hook up to each one of those transitions. e.g. MouseOver on enter, and on exit, MouseDown enter/exit, MouseUp enter/exit, MouseClicked enter/exit, etc.)
> 1 votes

# Answer
XOr can be your friend in this situation.

```
bool oldIsButtonUp = true;

void pollMouse(bool isButtonUp) {
    if ((oldIsButtonUp ^ isButtonUp) && isButtonUp) {
        sendMouseClickEvent();
    }
    oldIsButtonUp = isButtonUp;
}

```

This will call sendMouseClickEvent() whenever the mouse button state changes from false to true.
> 0 votes

# Answer
An XNA version of this code would be something like (simplified just to detect the mouse down event, to detect double clicks you will need something more sophisticated);

```
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 begins if the button 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);
}

```
> -1 votes

---
Tags: input, mouse, control
---


title: Dynamic audio score/music

text:
# Question
Title: Dynamic audio score/music
I'm interested in developing a game who's background music changes with the mood and scenario of the game's action. Of course many existing games do this (halo for example), but I was interested in any resources/papers/articles talking about the techniques to develop a system like this.

I have some ideas, and I understand that this will be equally challenging to implement at the code level as it will be to come up or acquire music that fits this model. Any links or, answers with ideas in them would he appreciated.

Edit: this is the kind of info I'm looking for :) http://halo.bungie.org/misc/gdc.2002.music/

# Answer
The earliest system I'm aware of is LucasArts's iMUSE system, used in most of the SCUMM games.

(That is a link to a patent document, but the patent has expired, leaving a very detailed description of how it worked available in the public domain. Hooray for the patent system actually working correctly for once!)
> 15 votes

# Answer
Create Digital Music has covered adaptive game music a couple of times; I think this article about Max/MSP and the Unity game engine is the closest to what you are looking for. It's also worth reading the comments, there are links to a lot more resources on this topic.
There is a more technical and in-depth article about game audio at Gamasutra, which discusses the use of Puredata, the open-source sibling of Max/MSP.
> 3 votes

# Answer
Here is a new interactive music system. psai Unfortunately not much detail as to the engineering design or content authoring pipeline at the time of this posting, however the resulting game-reactive music output is well demonstrated.

You are able to freely try out how things are done from an authoring-perspective in wwise or fmod designer, and these could be useful to assist initial composition your music assets while playing with different interactive authoring approaches before you commit to any particular design in your own engine.

There are many possible combinations of game actions and musical parameters that may be used to shape a composition interactively. Budgets of money time and target platforms are usually the limiting factors within which to scope an interactive music system.

From the audio standpoint you can produce the following types of music assets for different interactive music systems:

* Finished mixes of songs or song sections and transitions for end-to-end or cross-faded playback with optional timing metadata for exit / enter on-beat. This is the least amount of interactivity from a music-standpoint, but still it is sufficient for a great number of games.
* Finished mix stems of songs or song sections and transitions packaged as a multi-channel file or played together in sync to allow dynamic blending among the stems. These can also use timing metadata for on-beat switches and different realtime effects on the stems are now possible.
* Audio clips ranging from mix-stems down to individual instrument parts which are then arranged on an interactive music editor timeline to reconstruct the song sections and transitions. Such an arrangement provides much more granularity for bringing parts in and out of the mix as well as randomization and other dynamic effects within the library of parts.

The above have generally been limited to the base tempo and key as recorded in the audio files unless you allow dynamic bending of playback rate or implement a pitch-shift / time-stretch effect. Alternatively you could author a huge matrix of tempos / keys but that would be pretty wasteful from a data size and work effort standpoint.

* If you require the most granular level of music interactivity you can play back individual note sequences of wave data or synthesis algorithms. Here you can freely change arrangement, tempo, meter, key, instrumentation, synthesis parameters, mix and realtime effects for each part of the composition if you choose to build it all the way down to that level.
> 2 votes

# Answer
Noatikl from Intermorphic is generating some buzz and looks promising.

http://intermorphic.com/tools/noatikl/index.html

some history here:

http://intermorphic.com/tools/noatikl/generative\_music.html
> 0 votes

# Answer
Ooh! ooh! I want to do something similar! Once upon a time, I used to make some music with **ModPlug Tracker**, a windows version of earlier music trackers found in the Amiga scene.

Instead of recording and mixing down the music and compressing it, as you do an MP3, you give the computer a set of samples and a sequence of instructions for when and at what pitch to play the samples. These would be in pattern blocks that would be ordered. Being able to change from one set of patterns into another, and adjust separate channels' volumes on the way, I think would be the way to go.

Originally, the small file sizes resulted in mostly chip tunes, but given the size of things these days, and maybe adding an audio compression routine to the samples may enable some fairly fancy sound.
> 0 votes

---
Tags: audio
---


title: Issue with importing model to xna

text:
# Question
Title: Issue with importing model to xna
I am creating a model with Blender which looks like this:

and I am importing it into an XNA project. There seems to be some kind of transparency issue. The model looks like that:

When the camera looks on one side, the side is not shown. Why do I have this problem and what can I do to fix it?

PS: I am using a custom Effect but I don't think that the issue has something to do with that.

# Answer
Looks like it might be a face culling issue. Try turning off face culling:

```
 GraphicsDevice.RasterizerState = RasterizerState.CullNone;

```
> 2 votes

# Answer
Settings the cullmode to none is only a workaround. There is a problem within Blender that causes problems during export. Maybe you can send this model to blender community? So they are able to identify this bug in their software. By the way, you should never disable backfaceculling during your whole drawings, because you loose performance. So your code should look like the following:

```
//store last state
var oldResterizerState = GraphicsDevice.RasterizerState;
//set rasterizer to "solve" your bug
GraphicsDevice.RasterizerState = RasterizerState.CullNone;
//draw your buggy model now
....
//reset graphicsdevice to old state
GraphicsDevice.RasterizerState = oldRasterizerState;

```
> 0 votes

---
Tags: xna, models, blender
---


# Question
Title: XNA move from start position to target position exactly in 3D
If I have a list of positions that map out a path a character should follow. What would be the best way to move at a constant speed to each position making sure the character lands exactly at each position before moving onto the next?

For example the character is at position A, we then queue up position B and position C. The character cannot move towards position C until it reaches position B exactly.

It would be great if the solution worked at slower frame rates/update speeds as well.

# Answer
Why do you necessarily want the character to get to a point when a frame is drawn? You want your logic to be separated from view, that's why you use a timer and not onEnterFrame event, in first place. at smooth 30 FPS or more, a player won't see a difference.

What you want to do is not actually drawing the character on desired position, but behaving like if he was there. What you do now is probably calculating a `delta_time` everyframe by substracting old timestamp from an actual time: `delta_time = Now() - old_timestamp; old_timestamp = Now();`. And then using this data to move objects (e.g. `x += vx * delta_time`) etc. and then update them on screen. What you want to do in this case is to calculate objects (at least these that can be altered by the character's position) twice - at the moment the character reached a point, and at a moment right after, that is, delta\_time after previous frame:

1. Calculate when the character will come to point B (from A): `journey_time = distance / speed`.
2. On next frame, get the `delta_time` from previous frame.
3. If `delta_time >= journey_time` go to next point (4). Else `journey_time -= delta_time` and go to point 2.
4. Calculate everything for the moment the character reaches destination point, e.g. `simulatePhysics ( journey_time );`
5. Add actions special to the event (because you want to detect reaching the point for some particular reason I suppose), e.g. make the character ghostlike: `physics.removeChild ( character );`
6. Calculate second part of the 'frame': `simulatePhysics ( delta_time - journey_time );`.
7. Redraw the frame.
> 3 votes

# Answer
There is no solution that satisfies this demand precisely.

1. You would need to cap the framerate to a framefrate the player's machine can handle constantly. (the lowest framerate the game reaches when computation is heavy)
2. Calculate the distance from the current position to the first destination.
3. Divide that distance by the speed you wish the character to move at divided by the current framerate to get the amount of frames it would take to reach the destination. `distance / (speedPerSecond * (1.0/frameRate)) = framesLeft`
4. This could be a none integer number such as `framesLeft = 54.76`. We round this number to the nearest integer number `roundFrameCount = 55` and calculate a fake speed of `fakeSpeed = (distance / roundFrameCount)`.
5. We now move the object at this rate each frame.

Otherwise, when the object is too close to the first destination, you have to deduct the distance from that destination from the `stepSize = speed * delta` and use the rest of the `stepSize - distance` to move towards the next destination.
> 2 votes

---
Tags: xna, movement
---


# Question
Title: Is it must to use 3rd party framework to use to develop adobe stage3d game
I was searching for tutorials to develop games using stage3d. Every where I came across the articles/tutorials using the frameworks.

Is it compulsory to use the frameworks? or its very difficult to do it without frame works?

# Answer
> 1 votes
You could take a look how to do Stage3D without framework

http://www.packtpub.com/adobe-flash11-stage3d-molehill-game-programming-beginners-guide/book#overview

It is definitely easier to use framework, at least for me.

# Answer
> 0 votes
The fact you're asking the question and your Nickname makes it simple to answer that yes, you don't want to mess with low level molehill. Try Away3D, learn some general 3D concepts and only then think if it's worth to optimize your game by working with stage3D directly.

---
Tags: stage3d
---


# Question
Title: Is it possible to convert file from Blender 3d to svg?
I want to build web game in html5 with canvas/svg.

Can I convert/export file from blender to canvas/svg?

Maybe via unity3d?

# Answer
Try Three.js and use the Blender to JSON.
> 1 votes

# Answer
There is this - Blender to WebGL Javascript exporter
> 0 votes

---
Tags: html5, blender, html-canvas, svg
---


# Question
Title: What is balance needed between testing the game mechanic (play testing) and testing the code
I do not work in the industry and I wondered very broadly what percentage is given over to play testing versus getting the bugs out. Or does no-one really work it like this?

# Answer
> 2 votes
Those are quite different things and it's hard to give a definite percentage.

**QA** (≈ hunting bugs) is usually the job of a entire QA department, this can include several employees, and even several companies or locations. This is a day-to-day task: the earlier bugs get spotted, the earlier they get fixed, so the bug hunt is really running continuously. Usually this task is taking more and more space when production advances, from almost nothing in pre-prod to almost 100% when getting close to a gold master. E.g. at the end of a production, big studios take advantage of time zones to get daily builds tested overnight, literally from the other side of the world.

**Playtesting** on the other hand is something that's performed less often, but requires more preparation. For it to be useful, you need to find and select playtesters, you'll want them to match your target audience, and you'll have to prepare playtesting sessions to get the most useful information out of it. "Digesting" what gets out also takes some time. Because of those requirements, this is something performed occasionally, but regularly anyway (I'd say from two week to two months for a big studio). But that's for formal playtesting, everybody involved in making a game actually gives input on it on a daily basis: that's not something really measurable.

# Answer
> 0 votes
I don't think you can say "you need X percent play testing and Y percent bug testing", because there can't be a general formula for that. Maybe you're lucky and get the game mechanic right at the first or second try, or maybe you have to iterate a lot and end up going through dozens and dozens of playtest sessions.

Similar situations might be true for bug hunting sessions. Maybe your code is very clean and bug free to start with, or maybe you manage to hunt down most bugs in one or two sessions, or maybe you have bad luck and each time you fix one bug, another one emerges and it draws on and on.

Then there's the point that while you're playtesting, you might find some bugs as well, and when you're hunting for bugs you might notice some gameplay problems. So you can't even clearly separate the two.

It all really depends on the type of game you're making, the game itself, your ability and experience and maybe even a lucky choice of initial values for a lot of things.

---
Tags: game-design, playtesting
---


# Question
Title: Create Adventure Game Scene/Room/Backdrop from Real Photo
Is there a suitable software or a good tutorial for creating 2D rooms/scenery for adventure games from real photos?

Is it possible to achieve good results by using photos, or the hand-drawn style will always be the best choice?

Thank you!

--- EDIT ---

I want to clarify that I'm particularly interested in the art creation process, not on the environment in which to build games. I'm writing the game in Java for Android, but I don't think it matters.

Also, I'm not trying to decide if the game will have photo realistic rooms or not - I want to achieve 2d pixelated, old-school style background scenes and I wonder if this can be made from photos, because I cannot draw them myself.

For example, can I shoot a scene with my camera and then make it look something like the image in the following link:

PIXEL ART FOREST

I know that I cannot get the same quality as an absolutely hand-drawn pixel, but I'm looking for some decent technology/tutorial/software to make them somewhat similar.

# Answer
I won't say it is impossible, I will say it seems impossible but I love the idea and you should definitely try it.

I would start with duplicating the question on https://photo.stackexchange.com/

As for what techniques I would try:

* make a photo with a high contrast lightning, probably achieved by some back-light, e.g. a lamp hidden behind one of trees (or multiple lamps).
* then mess with RAW file achieving even more contrast
* apply some sharpening filters
* apply pixelizing filters - I think the effect will be best if the filters aren't applied to whole image, but only to a part of it
* apply some edge-tracing filters
* decrease color palette using weak dithering

With these, I could turn this into this. I like former better, but style obviously changed.
> 4 votes

# Answer
It is possible to create an adventure based on real photos. The question which is better, comic/hand-drawn style or realistic, depends on the style and content of your game. Myst is a fairly old but also popular example of realistic adventure games.

There are plenties of free solutions which helps you to create such a game.

If you are interested in the background or some concrete solutions please specify which programming language you are using, or if you just want some game maker like solution. A widely known solution is the Adventure Game Studio, which allows you to import your own backgrounds, define zones for click interaction and lay out a basic Point´n Click adventure. Hope this gets you started!
> 1 votes

---
Tags: 2d, graphics, adventure-games, scene
---