Hello, I am trying to write a very simple AI script that should have the AI object rotate towards the player. My code works except the AI rotates with an arc. I want it to sit still and rotate around the specified axis. Here is my code:
function Update () {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
myTransform.eulerAngles = Vector3(0, transform.eulerAngles.y, 0);
}
Also I should point out I want this to work without the use of a character controller. Can someone give me an idea how to make this work properly? Thank you!
It looks like you have what you need with the myTransform.rotation code. I’m unsure why you have the eulerAngles code in there at all. Here is a C# script I wrote up, using yours as a base, and it works very well. You just need to pass in the object (your enemy AI) that you want to rotate and follow the player in as ‘myTransform’, then pass in the object you want to be followed (the player) in as ‘targetTransform’.
using UnityEngine;
using System.Collections;
public class LookAt : MonoBehaviour
{
public Transform myTransform;
public Transform targetTransform;
public float rotationSpeed = 1.0f;
void Update()
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation, Quaternion.LookRotation(targetTransform.position - myTransform.position), rotationSpeed * Time.deltaTime);
}
}