__Move An Object Through A Set Of Points__
In order to move an objects through various points, we need a way to access those points.

So for accessing them we will use an array of transforms.

We will be using a Co-routine to update the object's position and to help it "Find Da Way".

I'm pretty sure by the time you read this that the meme is long dead.

While going through each point by lerping through each point may seem like a viable option but it leads to results like this:

Inconsistent speed of movement |

This type of movement where it takes the same amount of time to cover the same distance may not be the type of movement you are looking for.

First we will see how to get to this point then learn about the better way of moving stuff.

```
private IEnumerator MoveToSeat(Transform[] path)
{
float t = 0;
Vector2 startPostion;
float distance;
for (int i = 0; i < path.Length; ++i)
{
startPostion = transform.position;
t = 0;
while (t<= 1f)
{
t += Time.deltaTime * speed;
transform.position = Vector2.Lerp(startPostion, path[i].position, t);
yield return null;
}
transform.position = path[i].position; //Making sure flotaing point errors don't creep in
//t value might have overshot
}
}
```

Nothing really important to note here... other than that the Lerp function just takes into consideration the deltaTime value & the speed of movement.Now we will do it the right way by taking into consideration the distance between the points as well.

```
private IEnumerator MoveToSeat(Transform[] path)
{
float t = 0;
Vector2 startPostion;
for (int i = 0; i < path.Length; ++i)
{
startPostion = transform.position;
float distance = Vector2.Distance(startPostion, path[i].position);
t = 0;
while (t <= 1f)
{
t += (Time.deltaTime / distance) * speed;
transform.position = Vector2.Lerp(startPostion, path[i].position, t);
yield return null;
}
transform.position = path[i].position; //Making sure flotaing point errors don't creep in
//t value might have overshot
}
}
```

Now we get this result:Takes longer time to cover larger distance |

[Speed = Distance / Time ] : [ Time = Distance / Speed] & thereby we use 1/Time which is the increment value for time(t).

Support Bitshift Programmer by leaving a like on Bitshift Programmer Facebook Page and be updated as soon as there is a new blog post.

If you have any questions that you might have about shaders, C# or Unity development in general don't be shy and leave a message on my facebook page or down in the comments.

For more Unity tutorials go HERE.

I have found Da Way My Brodda

ReplyDelete