Sign in to follow this  
dsage

2d plaformer math

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;

or

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();
while(alive)
{
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

-Richardo

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this