# Move Towards Point

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

## 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 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 on other sites
Quote:
 Original post by CDTMDBelow 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 on other sites
Using float values for the player and that new formula I was able to get it working flawlessly. Thanks guys!

1. 1
2. 2
Rutin
16
3. 3
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• ### Forum Statistics

• Total Topics
633702
• Total Posts
3013450
×