I’m working on a movement system for my player that has the player moving between empty game objects, essentially nodes. My problem is trying to figure out how to code finding the next node in the series, right now its just 3 nodes but I may be adding in more later.
I’m thinking I’ll have to number the nodes as 1, 2, and 3, no problems there. My real trouble is if my player is on node 3, how do I create code that will search for the next node (#4) if the player is moving forward, or a previous node (#2) if moving backwards? Any tips or links I can use? Any nudges in the proper direction would be greatly appreciated!
Create an Array of nodes, and use an int named index to iterate through the array, using vector3.distance to check if you’ve reached the target destination and wait for the input to go forward or backwards.
Here’s a rough example of how this could be done (there are better ways with some planning, but this was done in like 5 mins)
public GameObject[] waypoints; // assign in inspector
private int curWaypointIndex = 0;
private GameObject _targetWaypoint;
// Use this for initialization
void Start ()
{
_targetWaypoint = waypoints[0]; // first node
}
// Update is called once per frame
void Update ()
{
MoveToTarget();
}
public void MoveToTarget()
{
if (!IsAtDestination(_targetWaypoint, transform.position))
{
transform.position = Vector3.MoveTowards(transform.position, _targetWaypoint.transform.position,
1.0f * Time.deltaTime);
}
else if (IsAtDestination(_targetWaypoint, transform.position))
{
// wait for input
//SelectTargetWaypoint();
if (Input.GetKeyDown(KeyCode.W))
{
SelectTargetWaypoint();
}
else if (Input.GetKeyDown(KeyCode.S))
{
SelectLastWaypoint();
}
}
}
public bool IsAtDestination(GameObject targetGameObject, Vector3 curPos)
{
if (Vector3.Distance(targetGameObject.transform.position, curPos) < .5f)
{
return true;
}
return false;
}
public void SelectTargetWaypoint()
{
if (curWaypointIndex < waypoints.Length)
{
curWaypointIndex++;
_targetWaypoint = waypoints[curWaypointIndex];
}
else
{
// no more waypoints prompt
}
}
public void SelectLastWaypoint()
{
if (curWaypointIndex > 0)
{
curWaypointIndex--;
_targetWaypoint = waypoints[curWaypointIndex];
}
else
{
// cannot move back prompt
}
}
Also, if you’re only moving towards waypoints it might be worth looking into the NavMeshAgent so you can have obstacle avoidance without having to programmatically tackle it