How to translate an object to a location slowly (so that it can be seen)

423 views Asked by At

In my game I have a player object and an enemy object. The enemy object, when initialized is supposed to find the current location of the player at that specific time and head towards that spot, ultimately passing or hitting the player at which point it'll go offscreen.

In order to do this I've figured I'm going to have to use trigonometry however I can't seem to figure out what to do as my equation for direction and speed never aligns with the position of the player.

Here's what I have..

    direction = Math.atan((this.X_POS-plr.X_POS)/(this.Y_POS-plr.Y_POS));

    speedX = (int) (speed * Math.cos(direction));
    speedY = (int) (speed * Math.sin(direction));
  • "this" is the enemy and "plr" is the player.
  • "direction" is the angle to the player
  • "speedX" and "speedY" is the amount to translate each game tick. (deltaX, deltaY)

Here's my rough notes if it helps:

enter image description here

If anyone has any idea how to properly do this I'd appreciate the help, thanks!

    //Inside the food/enemy class:
    //inside the constructor
    direction = Math.random() * 2.0 * Math.PI; //x/y position of player, xy position of food
    direction = Math.atan((this.X_POS-plr.X_POS)/(this.Y_POS-plr.Y_POS));

    speedX = (int) (speed * Math.cos(direction));
    speedY = (int) (speed * Math.sin(direction));

    //inside update position method
    X_POS += speedX;
    Y_POS += speedY;

    //inside draw player method
    g.setColor(rim);
    g.fillOval(X_POS-radius-3, Y_POS-radius-3, (radius*2)+6, (radius*2)+6);

    g.setColor(center);
    g.fillOval(X_POS-radius, Y_POS-radius, radius*2, radius*2);  

   //Inside the player class X_POS and Y_POS are set to 200 each.

Then, inside the run method of the main class every 15 milseconds the update position method and draw method is called.

1

There are 1 answers

0
Matt Walker On

Well, since nobody else seems to know how I found out how myself.

    direction = Math.atan2(plr.Y_POS - Y_POS, plr.X_POS - X_POS);

    speedX = (speed * Math.cos(direction));
    speedY = (speed * Math.sin(direction));

Thanks for the help!