Daniel Tian’s Professional Blog


Just another WordPress.com weblog

Bouncing triangle problem fixed

I managed to fix the bouncing triangle problem. I have a bouncing triangle on the lower right hand corner of my game. Normally it works fine, but when I drag the game window around, the triangle doesn’t reverse its direction and continues to travel in the last direction it was going in until I release the window. If I’ve been dragging the window for a while, the triangle will end up somewhere in the middle of the screen.

This is my code after the fix:

public void Update(GameTime gameTime)
    arrowMoveDistance = arrowDirection * new Vector2(0, (float)(gameTime.ElapsedGameTime.TotalMilliseconds / arrowBounceSpeedInMilliseconds));
    arrowTotalDistanceMoved += Math.Abs(arrowMoveDistance.Y);

    if (arrowTotalDistanceMoved >= arrowBounceDistanceInPixels)
        arrowDirection = -arrowDirection;
        arrowTotalDistanceMoved = 0;

    arrowCurrentPosition += arrowMoveDistance;

All I had to do was change gameTime.ElapsedRealTime.TotalMilliseconds to gameTime.ElapsedGameTime.TotalMilliseconds. It turns out that when you drag the window around, ElapsedGameTime stops updating but ElapsedRealTime still does, which makes sense because real time keeps on ticking when you move a window around. This is another case of one of those things where you don’t really think about it until it becomes a problem.

The reason why I originally decided to use ElapsedRealTime is because ElapsedGameTime will always return the same value, even if the code runs slower than it should. So for example, if ElapsedGameTime should take 16 ms to run (1/60 of a second) but actually takes 32 ms, ElapsedGameTime will still return 16 ms, but ElapsedRealTime will return the correct value, 32 ms. If the code takes less than 16 ms, both will return 16 ms because that is the time interval between update calls (assuming 60 FPS for the game). This isn’t so much of a problem when framerate is limited but can cause issues when Game.IsFixedTimeStep and GraphicsDeviceManager.SynchronizeWithVerticalRetrace are false, which removes the framerate limit. When the framerate is pushing up into the thousands, time-critical code can exhibit strange behavior if ElapsedGameTime is used because it doesn’t accurately reflect the amount of time that has passed.


Filed under: Uncategorized, , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: