0

Hello I am wondering how I would make an object move towards another object or point. Down here is a tick method which is set to update 60 times a second. It's just a basic thing which moves based on the change in x and y.

All help is appreciated, thanks.

public void tick() {
    x += dX;
    y += dY;

    if(y <= 16 || y >= Game.HEIGHT-62) velY *= -1;
    if(x <= 16 || x >= Game.WIDTH-39) velX *= -1;

    collision();
}
Meeesh
  • 992
  • 1
  • 8
  • 15
  • 2
    Something like [this for example](http://stackoverflow.com/questions/26784303/java-move-image-towards-mouse-position/26791886#26791886)? – MadProgrammer Feb 10 '15 at 01:10
  • Well yes, but i'm not sure how to implement that into my code. Right now I am playing around with different mathematical alogrithms but they don't seem to be working. This example seems a bit confusing because it does not directly answer my question. If you can could you show me how it should look in my code? Also if you too are confused, I am trying to have an enemy (which the tick method is a part of) follow the user. – Meeesh Feb 10 '15 at 02:16
  • Oh, it does, it allows one object to move towards another, it just so happens that one of the objects is the mouse. The magic happens instead the `ActionListener` of the `Timer`, `imagePosition.x += mousePoint.x < centerX ? -1 : 1;` when the x positions are not equal. Can you explain how the linked example doesn't answer your question... – MadProgrammer Feb 10 '15 at 02:19
  • OK, sorry my fault for being confused, I misunderstood the code, but I'm actually wondering how to make it smooth where the object will move in a straight line toward the object instead of just omnidirectionally – Meeesh Feb 10 '15 at 02:25
  • It depends on what you mean by straight line. The linked example essentially creates a beeline straight for the mouse. You could draw a line between the image and mouse and the image would walk it. – MadProgrammer Feb 10 '15 at 02:29

0 Answers0