Question

I'm doing a simple breakout game and I have some problem to understand how I should handle speed and direction of the ball to move it in different diagonal paths. I'm using this code in an update method:

xPos += xSpeed * direction;
yPos += ySpeed * direction;

If I use different vaules of xSpeed = 2 and YSpeed = 1 I can change to different diagonal paths, but I still want the same speed. If I increase value of xSpeed = 4 to get another diagonal path, then the speed is also increased, and I want the ball to move in the same speed. For the value of direction I use 1 or -1. But I guess it would be better to change the value of direction to get diagonal paths in degrees? In a breakout game the ball has to bounce back in the oppesite direction. I'm not good in math, so I would preciate some help to solve this. Any ideas how I can improve my code?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top