How do I calculate the angle of an object in java?

Asked

Viewed 144 times

-1

In case I am making a game and have a player and an enemy (the enemy does not move). I would like the enemy to always throw himself towards the player and for that I need to find the angle of the enemy.


import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.caique.main.Game;
import com.caique.main.Sound;
import com.caique.world.Camera;

public class Plant extends Entity{

    private int frames = 0, maxFrames = 10, index = 0, maxIndex = 1;
    private BufferedImage[] sprites;
    
    public static boolean isShooting = false;
    
    public Plant(int x, int y, int width, int height, BufferedImage sprite) {
        super(x, y, width, height, null);
        sprites = new BufferedImage[2];
        sprites[0] = Game.spritesheet.getSprite(16, 64, 16, 16);
        sprites[1] = Game.spritesheet.getSprite(32, 64, 16, 16);
        
    }

    public void tick() {
        
        frames++;
        if(frames == maxFrames) {
            frames = 0;
            index++;
            if(index > maxIndex) {
                index = 0;
            }
            
        }
        // Aqui aonde quero verificar se está atirando e calcular o ângulo.
        if(isShooting) {
            isShooting = false;
            double angle = Math.atan2(Game.player.y - (this.getY() + 8 - Camera.y), Game.player.x - (this.getX() + 8 - Camera.x));
            double dx = Math.cos(angle);
            double dy = Math.sin(angle);
            int px = 0;
            int py = 0;
                
            BulletShooting bullet = new BulletShooting(this.getX() + px, this.getY() + py, 3, 3, null, dx, dy);
            Game.bullets.add(bullet);
        }
        
    }
    
    public void render(Graphics g) {
        g.drawImage(sprites[index], this.getX() - Camera.x, this.getY() - Camera.y, null);
    }
}
  • that variable double Angle is completely wrong, okay?

  • the question is of mathematics and not of informatics. "Calculate the Angle between two points". Link [https://www.matematica.pt/geogebra/10-ano-pontos.php]

  • right but where that would apply in java, as I could do?

  • point A would be that and point B, and point C?

1 answer

1

Using Math.atan() returns the value in radians, but you need the value in degrees. Do the following to find the angle in degrees.

public double calculaAnguloEmGraus(double x, double y) {

        double radiano = Math.atan(y/x);

        // converter de radianos para graus
        double graus = Math.toDegrees(radiano);
        return graus;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.