How can I move an object (like a cube) towards another object?

Let's say that we have a red cube in the center of a floor, and a blue cube in another location, there aren't objects between this two, so the movement is along a line.

How can I move the blue cube towards the red one?

  • \$\begingroup\$ You could use Bresenham's algorithm if you don't want to use floating point (or if you're just worried about speed). \$\endgroup\$
    – Doorknob
    Jan 13, 2014 at 21:54

2 Answers 2


A basic solution to this problem, given the two positions of the objects (A and B):

  • Compute the normalized direction vector from A to B: v = normalize(B - A).
  • Every game logic update, add that vector v (scaled by the desired object speed) to the position of A: A += v * speed.
  • Stop doing this when A is within some desired tolerance of B.

A simple implementation of this might involve storing "movement destination" point with each object, representing where it is trying to get each frame. Apply the above logic every frame in the object's update method (pseudocode):

if (target is assigned && !position.isWithinToleranceOf(target)) {
  v = normalize(target - position)
  position += speed * elapsedTime * v;

A more involved solution would involve abstracting out the movement destination and handling into a more generic "orders" object which can be associated with an in-game entity, allowing you to build "movement order" objects and "attack order objects," all of which could be assigned to various in-game objects.

  • \$\begingroup\$ Vector3f direction = Vector3f.ZERO.subtract(creeper.getLocalTranslation()).normalize(); creeper.move(direction.mult(CREEPER_SPEED)); The creeper moves towards the center \$\endgroup\$
    – Fab
    Jan 13, 2014 at 22:00

I'm assuming you're using 2d vectors to accomplish this. If you are, it's very simple: Just give your moving object a velocity vector that points from its position towards the other object's position. It's easier to give it unit length, that way you can modify speed later on. Example:

this.velocity = other.position - this.position;
this.velocity *= 1/this.velocity.norm;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .