Jump to content
  • Advertisement
Sign in to follow this  

2d plaformer math

This topic is 4955 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Im usiong ddraw w/ c++... I use int's for my players position but im needing to change it so I can have them pove less than a pixle a second. I was going to use floats but I read/heard that I should use a system like playerxpos/100 to blt and add normally to change the position??? Is this the best way to do this? Or shoudl I stick with floats? Code snippits would be helpfull.
float fPlayerX = 0000.00
(int)fPlayerX += fVelX;


int PlayerX = 0;
PlayerX/100 == real number cord

Share this post

Link to post
Share on other sites
The method you described above (multiplying an float by 100 to make it an integer) is called fixed point mathematics (as opposed to floating point) and it used to be _the_ way to code games. But that was when 486's rocked the planet and even earlier. Nowadays, when processors can handle floating points almost as fast as they do integers, it is a waste of time. So, just use integers.

By the way, it seems like you are storing velocities (speeds) that are in pixels per frame. So that every time your main loop passes, your character moves 1 pixel (or 2 pixels or so). _that is not wise_. It makes your code speed machine dependant.

Instead, make your velocities in pixels/second. So that you might move 5 pixels per second, and multiply that by the time elapsed from the last time you moved it.

Pseudo code:

float x, y; /* the position of your character */
float vx, vy; /* the velocity of your character */

unsigned long startTime = GetTickCount();
t = (GetTickCount() - startTime) / 1000.0;
startTime = GetTickCount();

x += t * vx;
y += t * vy;

drawSprite((int)x, (int)y);

I think that GetTickCount() is a valid windows function, but I am a Linux/SDL programmer, so I'm not sure. However, GetTickCount() is a function (in the pseudo code) that returns the system time in milliseconds (1/1000 of a second).

Hope this helps.

Oh yeah, and if you're having trouble with directx/windows, take a look at SDL, it's simpler, better, needs less code, it's almost as fast and works on linux and a dozen other platforms. SDL homepage is at http://www.libsdl.org


Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!