Move Towards Point

Started by
2 comments, last by CDTMD 14 years, 2 months ago
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.
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.
[size=2]My Projects:
[size=2]Portfolio Map for Android - Free Visual Portfolio Tracker
[size=2]Electron Flux for Android - Free Puzzle/Logic Game
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;
Using float values for the player and that new formula I was able to get it working flawlessly. Thanks guys!

This topic is closed to new replies.

Advertisement