I am developing a racing game where I have a predefined path with waypoints, and what I want to achieve is, I want my player to follow that general direction of the path but still be in full control of my player. As in, it keeps following the path, But I should be able to move it left and right to avoid obstacles.
Here is the piece of code I use right now.
#region Following the path
if (PathGenerator.instance.wayPoints.Count > 0)
{
Transform currentNode = PathGenerator.instance.wayPoints[currentNodeCount];
transform.position = Vector3.MoveTowards(transform.position, currentNode.position, forwardSpeed * Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(currentNode.position - transform.position), 1 * Time.deltaTime);
float distance = Vector3.Distance(transform.position, currentNode.position);
if(distance < 1f)
{
if(currentNodeCount < PathGenerator.instance.wayPoints.Count - 1)
currentNodeCount++;
}
}
#endregion
But the issue here Is that the player goes directly to the waypoint, even if I move it left and right. It would just go back to the center of the waypoint. watch the gif:-
As you can see how it comes back to the center to follow the waypoint, I can't control the player like this. All I want is the player to follow the circuit path itself, but I want to control it's X-axis in order to avoid obstacle.
Can someone please guide me here and help me solve my problem? Any help or idea would be appreciated.
Thank you.
The below may not be the best solution to this problem, but shall help go further
You can setup the player as below
Player object with script and the character(capsule) as child please check below image
and then with below code you will be allowed to move character side ways keeping the main object follow the waypoint. Later you can add some limit to max side movement.
void Update()
{
//made a similar situation from your code
if (waypoints.Length > 0)
{
Transform currentNode = waypoints[currentNodeCount].transform;
transform.position = Vector3.MoveTowards(transform.position, currentNode.position, 10f * Time.deltaTime);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(currentNode.position - transform.position), 1 * Time.deltaTime);
float distance = Vector3.Distance(transform.position, currentNode.position);
if (distance < 1f)
{
if (currentNodeCount < waypoints.Length - 1)
currentNodeCount++;
}
}
// side movement to child object, in m case it is Player Object's second child
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.GetChild(1).Translate(Vector3.left * 5f * Time.deltaTime);
}
else if (Input.GetKey(KeyCode.RightArrow))
{
transform.GetChild(1).Translate(Vector3.right * 5f * Time.deltaTime);
}
}
Also attaching the output video Follow_waypoint_along_with_manual_side_movement
P.S. : This is my first answer, please forgive if not answered in correct format.