A
A
Andrey Klementiev2018-03-01 19:44:13
Java
Andrey Klementiev, 2018-03-01 19:44:13

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;
    }

The idea is that you need to create a variable that will contain the value of the angle between the direction vector and the trigonometric zero, for example. Pressing LEFT or RIGHT will change this value in one direction or another, respectively, the movement of the object in space along the coordinates will be determined using this angle and the speed of movement when the UP or DOWN keys are pressed. The problem is that I don't know how to implement this, since there is a lot of information on the net about how to rotate images in one direction or another in draw methods, but not objects. I can make it so that it will be displayed as I need, but in fact it will only rotate the image, and the actual position of the object in space will be different, which will lead to incorrect game situations when, for example, a tank crashes into the air, or it will catch on, if I understand it correctly, of course. Perhaps for some of you this will be familiar, or just a very easy task, please explain to me please how to implement this. Thank you for attention.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question