0
\$\begingroup\$

I have two Vector3 positions:

 Vector3 start = new Vector3(1f, 1f, 1f);
 Vector3 target = new Vector3(5f, 5f, 5f);

How do I transform gameobjects a fixed amount from start to target, say .1f?

This is easily done with percentages, because you can do:

var dist = target - start;
 var d = 5f; // 5 increments
 var step = dist / d;

 while (start != target) {
     start += step;
 }

How do you do this with Fixed, not percentage steps. Say I want to increment .1f in some direction:

 var dist = target - start;
 var step = new Vector3(.1f, .1f, .1f); //How do I determine the direction of the increment?

 while (start != target) {
      start += step; 
  }

Thanks

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

It's really simple: You already have the difference between target and start in the dist variable. Just normalize that vector3, multiply it by the step distance and then you can add it.

start += dist.normalized * stepDist

Note: The code will most likely loop forever. You should probably check the distance before adding the step.

float d = dist.magnitude;
if (d<stepDist)
    start = target;
else
    start += dist.normalized * stepDist
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, it worked. I do some Vector3.Distance calculation in the while loop now to prevent infinite loops (basically is the distance between start and target greater than some float then perform while loop). \$\endgroup\$
    – shell
    Sep 16, 2017 at 2:29

You must log in to answer this question.

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