Hello!
I’ve started working on my first Unity project and could use some help.
It’s a top-down 2D game not unlike the UFO tutorial with enemies that should be moving between waypoints I specify with empty gameobjects per scene.
The following code worked well in an early prototype I made inside the the Roll-a-Ball Tutorial which is 3D, but doesn’t work in my actual 2D game:
using UnityEngine;
using System.Collections;
public class Enemy2AI : MonoBehaviour
{
public GameObject[] waypoints;
public int num = 0;
public float minDist;
public float speed;
// Update is called once per frame
void Update()
{
float dist = Vector3.Distance(gameObject.transform.position, waypoints[num].transform.position);
if (dist > minDist)
{
Move();
}
else
{
if (num + 1 == waypoints.Length)
{
num = 0;
}
else
{
num++;
}
}
}
public void Move()
{
gameObject.transform.LookAt(waypoints[num].transform.position);
gameObject.transform.position += gameObject.transform.forward * speed * Time.deltaTime;
}
}
Reading various Unity Answers posts it seems like a lot of people seem to have trouble transitioning from 3D to 2D because LookAt doesn’t work as expected. I’ve already tried a lot of the suggested workarounds, but couldn’t get any of them to work for my specific case.
I’d really appreciate if someone could help me recreate the behavior of my script in 2D by suggesting a different form of waypoint system or providing an alternative way to achieve what LookAt does for 3D.
Thanks in advance!