Question

So, I'm making a game where you are to outrun enemies. Instead of having the enemies move at only up, down, left, right, and at 45 degree angles, I want the enemy to take the shortest linear path towards the player. Here's 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 this does is sets the velocity in cardinal directions. What could I do to make this more accurate?

Was it helpful?

Solution

Assuming you have the position of the player and enemy, and you want the enemy to always have a velocity of 3, then pull out your 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);

What is this code doing, you ask? It's forming a triangle between the enemy and the player. You want the enemy to travel at 3 units/sec in the direction of the hypotenuse, so what you need to do is break that down into components that are parallel to the X and Y axes.

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

The floats h, a and o represent the hypotenuse, adjacent, and opposite sides of the triangle.

a/h is the velocity component parallel to the X axis.

o/h is the velocity component parallel to the y axis.

OTHER TIPS

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;

Calculates a vector pointing towards the position of palyer with a length of spd

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top