Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Entity move towards a x and y?

Tags:

java

I am looking for a way to make my Entity(A bullet) move towards a x and y,which is where the player was when the bullet was fired. so In my entity class i have -

   float xSpeed = 1.0F;
   float ySpeed = 0.0F;

if I wanted to move the entity in a diaganal line I would make xSpeed and ySpeed = 1.0F How would I make it move in the dir of another x and y?

Thanks for the help EDIT -- Solved,thanks for the help To anyone else who finds this question needing help,here is my code-

    float xSpeed = 0;
    float ySpeed = 0;

then I have some maths to make it so they move at the same speed

   ySpeed =  ySpeed * (float) (2.5 / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));
   xSpeed = xSpeed * (float) (2.5 / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed));

and this code to set the xSpeed and ySpeed,based on a x and y you want to move towards

    xSpeed = (Game.PlayerX - x) / 3;
    ySpeed = (Game.Playery - y) / 3;

and then,finaly,add xSpeed and ySpeed to the x and y of your entity

    this.x += xSpeed;
    this.y += ySpeed;
like image 722
Jack Patrick Avatar asked Nov 30 '25 10:11

Jack Patrick


1 Answers

The usual way is to set the relative x and y speeds to cover the required x and y distances in the allotted travel time:

float xSpeed = (targetLocation.x - currentLocation.x) / travelTime;
float ySpeed = (targetLocation.y - currentLocation.y) / travelTime;

If you want to travel at a predetermined speed, rather than in a predetermined travel time, do the above computations with travelTime set to some arbitrary value (1.0f would work fine, so you could simply eliminate the division). Then compute this factor:

float factor = desiredSpeed / Math.sqrt(xSpeed * xSpeed + ySpeed * ySpeed);

(Note that you'll be dividing by zero if xSpeed and ySpeed are both 0, but that simply indicates that the current and target locations are identical. If that's a possible condition, you should include an appropriate check.) Finally, readjust xSpeed and ySpeed by the factor:

xSpeed *= factor;
ySpeed *= factor;

Note that by setting travelTime to 1, this is just a sneaky way of multiplying the predetermined speed by the sine and cosine of the angle that the travel direction makes with the x axis without mentioning trigonometry at all. :)

like image 126
Ted Hopp Avatar answered Dec 09 '25 00:12

Ted Hopp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!