Sign in to follow this  
CDTMD

Move Towards Point

Recommended Posts

I need some help with some trigonometry. I use this code in SDL to make the player move towards a destination point. float fY = desY-playerY; float fX = desX-playerX; float dir = atan2(fY, fX)*180/PI playerX += cos(dir*PI/180)*speed playerY += sin(dir*PI/180)*speed In flash this code works fine. I can't find anything wrong with this mathematically. But it doesn't work. Below this start point it doesn't move at all. Above the start point it acts weird. It will either move up THAN right instead of together in a diagonal movement or it will move up and then stop. I have no idea what is wrong with my formula. Please help me.

Share this post


Link to post
Share on other sites
I don't see anything wrong with those 5 lines.

Use a debugger and watch your variables as you step through. This is something you should be able to find pretty easily I think.

Share this post


Link to post
Share on other sites
Quote:
Original post by CDTMD
Below this start point it doesn't move at all. Above the start point it acts weird. It will either move up THAN right instead of together in a diagonal movement or it will move up and then stop.

Such behaviour may happen if integer and floating types are mixed improperly. E.g. sin/cos returns numbers close to 0 and speed isn't great enough to make something above 1, and playerX/playerY is of an integer type so that the compiler converts the small offset to 0. In Flash the variables are probably of a generic Any or Number type internally, so that floats are not converted. Please check this.

However, the used method is worse w.r.t. performance. There are 3 trigonometric functions involved just to normalize a 2D vector (besides the fact that the float variants atan2f, sinf, cosf would be sufficient for float arguments). But how about using vector math? E.g. something like
float fX = desX-playerX;
float fY = desY-playerY;
float dist = sqrtf( fX*fX + fY*fY );
float step = speed/dist;
playerX += fX*step;
playerY += fY*step;

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