Reputation: 351
I am making a game in libgdx(java) where squares chase the main player. I can't figure out how to make the squares move in a straight line directly to the player at a constant speed. this means i want the squares to travel the same distance every second. I make a variable and set it equal to chasePattern1
. saidvariable[0]
is added to the enemies x
value, and saidvariable[1]
is added to the enemies y
value.
private float[] chasePattern1(float enemy_x,float enemy_y,float speed){
float[] returnvalue={0,0};
if(enemy_x>mainsquare.getX()){
returnvalue[0]=-1*speed;
}
if(enemy_x<mainsquare.getX()){
returnvalue[0]=speed;///does float work?no
}
if(enemy_y>mousey){
returnvalue[1]=-1*speed;
}
if(enemy_y<mousey){
returnvalue[1]=speed;
}
return returnvalue;
}
Upvotes: 1
Views: 1470
Reputation: 3125
if d
is the distance between the player and a square, v
is the velocity that you want the squares to move at, (x1,y1)
is the position of the player and (x0,y0)
is the position of the square, then
vx = (x1 - x0) * v / d
vy = (y1 - y0) * v / d
where vx
and vy
are the values that you need to add to the square's coordinates every second.
You can view it like this: If you want to travel from your position to the destination d
"points" with a speed of v
, it would take you t=d/v
moves.
Now, the distance you have to travel horizontally is x1-x0
and the distance vertically is y1-y0
, if you want to travel both distances in t
moves, you need to divide each distance in t
pieces and that's the speed for each component (x
and y
). When you divide x1-x0
for t
, you get that value, same for y
Upvotes: 6
Reputation: 2497
Here is what you want to do conceptually.
You want to create a vector in the direction your AI is going to move. That would be a vector in the direction connecting the AI to the player. Then, scale the vector so that it has length 1. Then multiply that vector by the constant speed of the AI.
Here's some pseudocode
AI_SPEED = 5
v = [ player.x - ai.x , player.y - ai.y ]
len = sqrt( v.x*v.x + v.y*v.y )
dir = [ v.x / len , v.y / len ]
movement = [ dir.x * AI_SPEED , dir.y * AI_SPEED ]
ai.x += movement.x;
ai.y += movement.y;
Upvotes: 2