Answer the question
In order to leave comments, you need to log in
How to correctly implement the rotation and movement of the figure?
Good day to all.
The essence of the task is to implement the rotation of a figure (for example, a triangle) to the left or right by N degrees.
In this case, the movement itself should be carried out with only one button. And the triangle will go in different directions depending on the rotation.
That is, when you press, say, the W key, the triangle moves forward depending on its current rotation. If I need to turn left, then I first press the A key and with it I also press the W .
I need to make an analogue of the game Asteroids
. How is it better to implement such an algorithm, since nothing comes to mind on my own?
PS: Please use c-like or python. Well, an algorithmic language or pseudocode would work too.
Thank you in advance.
Answer the question
In order to leave comments, you need to log in
These are basic elementary things - use trigonometry. If the direction is d degrees (from the horizontal axis) and you need to move along it by a distance s, then the changes along the axes are:
dx = s*cos(d);
dy = s*sin(d);
Typically, the arguments to the cos and sin library functions are given in radians. So, if you have d in degrees, then it must be multiplied by Pi / 180.0
The same sines and cosines must be used to draw a triangle. If the coordinates of the center are x0, y0 - then the coordinates of the apex will be
x0+triangle_size*cos(d);
y0+triangle_size*sin(d);
The other two vertices are built in exactly the same way, but, for an elongated shape, a different constant multiplier is needed and the angles there will be d + 120.0 and d-120.0 (different angles will give a different triangle shape).
Accordingly, the algorithm - when you press the rotate button, increase or decrease d. When you press the move button, shift the coordinates of the triangle by (dx, dy).
More advanced and faster solutions use rotation matrices. But the easiest way to understand this is that you don't count cos(d) and sin(d) each time. And store their values. When rotating through the alpha angle, you will need to calculate the new values using the standard trigonometric formulas from the old values:
cos(d+alpha) = cos(d)*cos(alpha) - sin(d)*sin(alpha);
sin(d+alpha) = cos(d)*sin(alpha) + sin(d)*cos(alpha);
The beauty of this method is that with a fixed alpha angle step, you only need to calculate the sine and cosine once for alpha, and then use them everywhere in the conversion.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question