- Home /
Waypoint navigation in 2D without LookAt
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!
Answer by juicyz · Sep 28, 2016 at 12:17 AM
You could do what LookAt does. Use math and find the needed rotation between you and the next waypoint then rotate your transform based on that.
There are a lot of answers for this already. Search the forums, answers, or google. http://answers.unity3d.com/questions/585035/lookat-2d-equivalent-.html Personally I like, transform.right = target.position - transform.position; Use the right transform.right/up/down/forward etc for your needs.
Answer by kuivalappa · Mar 17, 2017 at 12:15 PM
try this one
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class EnemyWaypoints : MonoBehaviour {
public List<Transform> waypoints;
private Transform currentWaypoint;
public float speed = 5f;
private float closeEnouth = 0.5f;
int point = 0;
void Start()
{
currentWaypoint = waypoints[point];
}
// Update is called once per frame
void Update()
{
Quaternion rotation = Quaternion.LookRotation(waypoints[point].position - transform.position, transform.TransformDirection(Vector3.forward));
transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);
float dist = Vector3.Distance(waypoints[point].position, transform.position);
transform.position = Vector3.MoveTowards(transform.position, waypoints[point].position, Time.deltaTime * speed);
if (Vector3.Distance(this.transform.position, waypoints[point].position) < closeEnouth)
{
if (point + 1 < waypoints.Count)
point++;
}
}
}