Friday, November 16, 2018

java - How can I move an object towards another along a straight line


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?



Answer




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.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...