Hello, Unity forum!
I am currently working on a 2D game where we need enemy AI’s to be able to move and “look” in different directions and I was wondering if you could help me out with some of the code for it.
This is what I have for code in my enemy movement behavior so far, it’s probably really crude but it’s just what I am able to do at my current skill level:
public class EnemyMovement : MonoBehaviour
{
public Enemy enemy;
public bool patrolingEnemy = false;
public float ppRadius = 1.0f;
public GameObject[] patrolPoints;
[HideInInspector]
public GameObject target;
[HideInInspector]
public GameObject player;
private int currentIndex = 0;
[Range(0, 5)]
public float movementspeed;
// Update is called once per frame
void Update()
{
if (patrolingEnemy == true && player == null)
{
//Enemy movement.
if (Vector3.Distance(patrolPoints[currentIndex].transform.localPosition, transform.localPosition) < ppRadius)
{
currentIndex++;
if (currentIndex >= patrolPoints.Length)
{
currentIndex = 0;
}
}
target = patrolPoints[currentIndex];
//Add enemy turn here to look at next patrol point here
}
else if (player != null)
{
target = player;
//Add enemy turn to look at player here.
}
else
{
target = gameObject;
}
transform.localPosition = Vector3.MoveTowards(transform.localPosition, target.transform.localPosition, Time.deltaTime * movementspeed);
}
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player")
{
player = collision.gameObject;
}
}
void OnTriggerExit2D(Collider2D collision)
{
player = null;
}
}
So I’ve tried a few different snippets people have suggested online but I can’t seem to get any of them to work. Some of the ones I have tried are:
transform.right = target.transform.localPosition - transform.localPosition;
And
Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90);
As well as some variation of these.
I guess what I am really after is just some piece of code that can help me rotate the Y-axis of the object 180 degrees depending on which direction the enemy is looking since they aren’t meant to be able to rotate in the z axis or the x-axis.
Thanks for the read-through.