2
\$\begingroup\$

I might be missing some simple thing but I'm not I am able to wrap my head around this. Normally, if I want to move two objects to different positions so they arrive at the same time I would use a lerp like so:

var speed = 2.0f;
var amount = Math.Min(1f, this.elapsedTime * speed);

var obj1NewPosition = Vector2.Lerp(this.obj1Start, this.obj1End, amount);
var obj2NewPosition = Vector2.Lerp(this.obj2Start, this.obj2End, amount);

this.obj1Position = obj1NewPosition;
this.obj2Position = obj2NewPosition;
this.elapsedTime += dt;

But I want to do this in a way where I only add to their positions:

var speed = 2.0f;

this.obj1Position += obj1Vector * speed * dt;
this.obj2Position += obj2Vector * speed * dt;

// obj1Vector is a normalized vector headed to obj1End
// obj2Vector is a normalized vector headed to obj2End

How do I make the second approach work such that each object will arrive at the destination I choose at the same time by only adding to their positions?

I don't have to consider acceleration or deceleration, simply: have two objects arrive at their respective destinations at the same time and then stop.

\$\endgroup\$
2
  • \$\begingroup\$ Is there any reason that you don't want to use lerp? \$\endgroup\$
    – Honeybunch
    Nov 15, 2015 at 21:26
  • \$\begingroup\$ @Honeybunch Yes, I can't set the position because other code will change the position later in the update. So if I lerp to a position it will override behaviour done by other code. \$\endgroup\$
    – test
    Nov 15, 2015 at 21:27

1 Answer 1

6
\$\begingroup\$

You need something like this?

//first get their distances between their destinations. E.g:
var d1 = 150.0f;
var d2 = 200.0f;
var speed1 = 2.0f;

/* Extra part */
//------------------------------------------------------------------
if(d1 == 0 && d2 != 0) d1 = d2;          // To avoid 'divide zero' error.
if(d1 == 0 && d2 == 0) ShutDownYourPC(); // ;) No need to explain
//------------------------------------------------------------------

var speed2 = speed1 * d2/d1;        // This is the important point

this.obj1Position += obj1Vector * speed1 * dt;
this.obj2Position += obj2Vector * speed2 * dt;
\$\endgroup\$
5
  • \$\begingroup\$ Gah. So simple, this worked for me. \$\endgroup\$
    – test
    Nov 15, 2015 at 21:49
  • \$\begingroup\$ Although easy to solve, I commend you and up vote it for the simplicity and cleanness of that answer. \$\endgroup\$
    – MAnd
    Nov 16, 2015 at 1:08
  • \$\begingroup\$ Beware when d1 ends up zero, as you'll end up with infinite speed for your second object. \$\endgroup\$ Nov 16, 2015 at 14:36
  • \$\begingroup\$ Yes, don't forget to check it. Even so I edit the code. \$\endgroup\$ Nov 16, 2015 at 18:04
  • \$\begingroup\$ Simple yet effective. +1 \$\endgroup\$ Nov 19, 2015 at 15:35

You must log in to answer this question.

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