I created a PathFollower script to move an object along a set of nodes. It works mostly as intended but there are some quirks i could really use some help with:
-
SOLVED The object doesnt reach the final node
-
SOLVED My code for looping (from the last to first node) is very clumsy and isn’t dynamic
-
It would be cool to control the amount of time the object spends at a node in the editor. Even better if it can be different from node to node.
The object will be a metro train in a 2D platform type game. The train arrives coming from the right. Stops and exits left. Then loops back outside of view in the bottom of the scene. I posted a video in my 2nd post showing this.
Thanks in advance for any help offered, the relevant scripts below:
using System.Collections;
using UnityEngine;
public class PathFollower : MonoBehaviour
The PathFollower Script
{
Node[] PathNode;
public GameObject MovingObject;
public float MoveSpeed;
float Timer;
//holds current node position
[SerializeField] int CurrentNode;
// static
[SerializeField] public static Vector3 CurrentPositionHolder;
void Start()
{
//Get Node children (from hierarchy)
PathNode = GetComponentsInChildren<Node>();
CheckNode();
}
//function to check current node an move to it,
//by saving the node position to CurrentPositionHolder
void CheckNode()
{
if (CurrentNode < PathNode.Length - 1)
{
Timer = 0;
// CurrentNode Position is put in CurrentPositionHolder
CurrentPositionHolder = PathNode[CurrentNode].transform.position;
Debug.Log(PathNode);
}
//Looping back
if (CurrentNode == 4)
{
Debug.Log("Node = 4, let's go back");
CurrentNode = -1;
}
//At the station (slower)
if (CurrentNode == 1)
{
MoveSpeed = 0.01f;
Debug.Log("Speed inside station");
}
//Outside station (faster)
if (CurrentNode != 1)
{
MoveSpeed = 0.05f;
Debug.Log("Speed outside station");
}
}
// Drawing lines in editor
void DrawLine()
{
for (int i = 0; i < PathNode.Length; i++)
{
if (i < PathNode.Length - 1)
{
Debug.DrawLine(PathNode[i].transform.position,
PathNode[i + 1].transform.position, Color.blue);
}
}
}
void Update()
{
DrawLine();
Debug.Log(CurrentNode);
// This makes the thing move
Timer += Time.deltaTime * MoveSpeed;
if(MovingObject.transform.position != CurrentPositionHolder)
{
// If MovingObject not at node, move to node
MovingObject.transform.position =
Vector3.Lerp(MovingObject.transform.position, CurrentPositionHolder, Timer);
}
else
{
if (CurrentNode < PathNode.Length - 1)
{
// If MovingObject is at Node, move to next
CurrentNode++;
CheckNode();
}
}
}
}