After some head scratching, i finally achieved this solution:
[SerializeField] float speed = 10f;
List<Waypoint> path;
int waypointCounter = 0;
void Start()
{
path = FindObjectOfType<Pathfinder>().GetPath();
}
private void Update()
{
MoveToWaypoint(path[waypointCounter]);
}
private void MoveToWaypoint(Waypoint waypoint)
{
Vector3 groundPos = new Vector3(transform.position.x, 0f, transform.position.z);
Vector3 direction = (waypoint.transform.position - groundPos).normalized;
float distanceThisFrame = speed * Time.deltaTime;
if (distanceThisFrame >= Vector3.Distance(waypoint.transform.position, groundPos))
{
waypointCounter++;
return;
}
transform.Translate(direction * distanceThisFrame, Space.World);
}
I use a “virtual position” (groundPos) that allows me to set different heights for future different types of enemies, thus keeping the grid based position and the actual position of the ship independent from each other.
I have some questions though:
-
I’ve seen solutions from other people in the Q&A section of the course (Lesson 156) and all of them use nested coroutines called in the start method. Are there any differences in performance in doing so?
-
I can’t find a solution to just loop through the list of waypoints in with a for statement instead of keeping track of the waypointCounter as a member variable. Any hint?
- Difference in performance/usage between Vector3.Translate and Vector3.MoveTowards ?
Thanks alot.