I need a help from you. I guess i need to do this in coroutine but i am not sure how to do it. I am making a Ludo (Don’ Get Angry Man) type of game. I need to move a character from point A to point B to point C and so on. I will have 40 GameObjects array that is named waypoints. Now let say character needs to move from current position in 5 steps. For example player is at waypoints[5].transform.position and how to move it from there to waypoints[10].transform.position. Character need to move from waypoints[5] to waypoints[6] to waypoints[7] and so on until reaches waypoints[10]. Character can move from point to point every 1 second.
This is how I would approach it. You can call MoveTo in an Update statement, and each frame your transform will move along the array of transforms until reaching your destination, where it returns true so that you can take your next action.
Transform[] waypoints;
//represents our current position in the array of waypoints
//increments by 1 as we move
int currentLocation = 1;
//next transform to move to
Transform nextWaypoint;
//move speed between transforms
float speed = 1;
//movementPercentage represents how far between 2 transforms we are from 0 to 1
float movementPercentage = 0;
Update()
{
if (MoveTo(10))
{
//We made it
}
}
//Pass the position of the array you want to move to
bool MoveTo(int destination)
{
if (waypoints[destination] = waypoints[currentLocation])
{
//we reached out destination
transform.position = waypoints[destination].position;
return true;
}
//Are we moving up in the array increment by 1, else decrement by 1
nextWaypoint = (destination > currentLocation)?waypoints[currentLocation + 1]: waypoints[currentLocation - 1];
movementPercentage += speed * Time.deltaTime;
if (movementPercentage >= 1)
{
//we have reached the next transform
//Are we moving up in the array, ++, else --
currentLocation = (destination > currentLocation) ? currentLocation+1:currentLocation-1;
movementPercentage = 0;
}
transform.position = ExactPos();
return false;
}
//Return the exact position for our transform, between 2 transforms
Vector3 ExactPos()
{
float x = Mathf.Lerp(waypoints[currentLocation].position.x, nextWaypoint.position.x, movementPercentage);
float y = Mathf.Lerp(waypoints[currentLocation].position.y, nextWaypoint.position.y, movementPercentage);
float z = Mathf.Lerp(waypoints[currentLocation].position.z, nextWaypoint.position.z, movementPercentage);
return new Vector3(x, y, z);
}