Answer the question
In order to leave comments, you need to log in
How to properly rotate a tank in a 2D game in Java?
Good day to all! More recently, I began to master programming, so if it hurts your eyes, I'm sorry. I decided to make a 2D game in Java using the information available on the network, but I ran into one problem. I would like to implement the movement of the player (in this case, the tank) not so that when one or more buttons UP, DOWN, LEFT and RIGHT are pressed, the tank instantly changes direction and moves in it, but somewhat close to reality, namely in such a way that the corresponding keys LEFT and RIGHT would rotate the object in one direction or another, and move it with the UP and DOWN keys. My Player class itself, namely its update method, looks typical:
public void update(){
if(up && y>0) dy = -speed;
if(down && y<GamePanel.HEIGHT -h) dy=speed;
if(right && x <GamePanel.WIDTH - w) dx = speed;
if(left && x>0) dx = - speed;
if (up && left || up && right || down && left || down && right ) {
double angle = Math.toRadians(45);
dy = dy * Math.sin(angle);
dx = dx * Math.cos(angle);
}
y += dy;
x += dx;
dy = 0;
dx = 0;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question