Vector motion in Java

So, I am making a game in which you must be ahead of the enemies. Instead of the enemies moving only up, down, left, right and at an angle of 45 degrees, I want the enemy to take the shortest linear path to the player. Here is my code:

public void moveEnemy() {
    if (player.pos.x > enemy.pos.x) {
    enemy.vel.x = 3;
    }
    if (player.pos.x < enemy.pos.x) {
    enemy.vel.x = -3;
    }
    if (player.pos.y > enemy.pos.y) {
    enemy.vel.y = 3;
    }
    if (player.pos.y < enemy.pos.y) {
    enemy.vel.y = -3;
    }
    if (player.pos.x == enemy.pos.x) {
    enemy.vel.x = 0;
    }
    if (player.pos.y == enemy.pos.y) {
    enemy.vel.y = 0;
    }
}

So, what does it mean, sets the speed in cardinal directions. What can I do to make this more accurate?

+4
source share
2 answers

Assuming you have a player and enemy position, and you want the enemy to always have speed 3, then pull out the trigonometry textbook and do the following:

float h = Math.sqrt(Math.pow(enemy.pos.y-player.pos.y,2) + Math.pow(enemy.pos.x-player.pos.x,2));
float a = player.pos.x - enemy.pos.x;
float o = player.pos.y - enemy.pos.y;
enemy.vel.x = 3f*(a/h);
enemy.vel.y = 3f*(o/h);

, ? . , 3 / , , X Y.

http://www.mathwords.com/s/sohcahtoa.htm

h, a o , .

a/h - , X.

o/h - , y.

+1
double spd=3;
double vX=player.pos.x-enemy.pos.x;
double vY=player.pos.y-enemy.pos.y;
double distance=Math.sqrt(vX*vX+vY*vY);
enemy.vel.x=vX/distance*spd;
enemy.vel.y=vY/distance*spd;

, palyer spd

0

All Articles