Jump to content
  • Advertisement
Sign in to follow this  
CDTMD

Move Towards Point

This topic is 3117 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

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
Advertisement
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
Using float values for the player and that new formula I was able to get it working flawlessly. Thanks guys!

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!