Math question about asteriods physics

Started by
11 comments, last by Lethian 22 years, 11 months ago
I personally use the KeyUp and KeyDown messages to set a set of flags for rotation, thrust, shooting, etc. In other words, when the thrust key is pressed, a flag like is_thrusting is set to true. When the key is released the flag is set to false. Now, in the game loop you just check flag. If it''s true, you add speed to the ship. If it is false, you don''t do anything, or, if you want the ship to slow, you substract speed from the ship.
<span class="smallfont">That is not dead which can eternal lieAnd with strange aeons even death may die.   -- "The Nameless City" - H. P. Lovecraft</span>
Advertisement
To limit the speed of my asteroids-style spaceship, and to slow it down when not thrusting, I implemented the idea of "friction" in space. Try the following method:

  • Assign your spaceship a "friction" value to reflect how aerodynamic it is.

  • Store your ships''s velocity as a vector.


  • Then, for every frame:

  • If thrusting, calculate the new velocity vector using sin/cos, as in previous messages.

  • Whether thrusting or not, calculate a "friction vector" by taking the opposite of the velocity vector (swap the signs of the X and Y component) and multiplying this vector by the ship''s "friction" constant.

  • Add this friction vector to the velocity vector.

  • Update the ship''s position by adding the velocity vector.


  • This method may sound a bit complicated but it is not too hard to implement, especially if you have a vector class defined. It effectively introduces a force representing friction, acting in the oppostite direction to the ship''s direction of travel, which will slow the ship when the player is not thrusting and will limit the ship''s maximum speed, depending on the values you assign to the ship''s thrust and friction. You can tweak these values until the ship behaves just the way you like, or alter them in-game to simulate different environments or represent "speed boost powerups" for example.

    Hope this helps,

    Moot
    And another thing, try and ensure that your calculations are all time-dependent, ie they are calculated according to how much time has elapsed since the last frame. This will ensure that your objects will travel at the same speed no matter how fast or slow the pc on which your game is running.

    For more details search GameDev for phrases like "QueryPerformanceCounter", "TimeGetTime" and "GetTickCount".

    Moot

    This topic is closed to new replies.

    Advertisement