You could use sine
and cosine
functions to get the relative movement in x
and y
axis.
Like:
xPos += speed * Math.sin(movementAngle);
yPos += speed * Math.cos(movementAngle);
Using the above (polar coordinates) in various animations has the advantage of ease in modyfing direction or velocity of movement (which are speed
and movementAngle
variables respectively). When using cartesian coordinates (x
and y
position), change in either velocity or direction of movement would require non-obvious changes to both x
and y
.
Formulas in the solution above are nothing more than conversion from polar to cartesian coordinates.
Edit: to get the more "natural" behaviour, when movementAngle
of 0
means moving right, PI/2
- up, PI
- left and 3*PI/2
- right, use the following:
xPos += speed * Math.cos(-1*movementAngle);
yPos += speed * Math.sin(-1*movementAngle);