Hello,
I have a question regarding Quaternion.LookRotation, I have two scripts that by the way I like to find ways to keep them as simple as posible, now the first one is a simple look at mouse position here is the code:
void Update ()
{
//get the mouse position
Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//Rotate toward the mouse position
//note that rotations are delt best wth quaternions
Quaternion _rotation = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward);
//set the new quaternion rotation to this transforms rotation
this.transform.rotation = _rotation;
//zero out the x and y angles so there is no skewing on the sprite
//note the euler angles are in degrees not radians or quaternions
this.transform.eulerAngles = new Vector3(0, 0, this.transform.eulerAngles.z);
}
This works exactly the way it should the object rotates towards the mouse position nice!!
Now I want to make an enemy look at my player if he enters its trigger collider so I figured the above code would work but it did not…
public Transform target;
public float rotationSpeed;
private bool isLooking = false;
void Update()
{
if (isLooking)
{
//get the targets position
Vector3 targetPosition = target.position;
//Rotate toward the mouse position
//note that rotations are delt best wth quaternions
Quaternion _rotation = Quaternion.LookRotation(this.transform.position - targetPosition, Vector3.forward);
//set the new quaternion rotation to this transforms rotation
this.transform.rotation = _rotation;
//zero out the x and y angles so there is no skewing on the sprite
//note the euler angles are in degrees not radians or quaternions
this.transform.eulerAngles = new Vector3(0, 0, this.transform.eulerAngles.z);
}
}
void OnTriggerEnter2D(Collider2D other)
{
isLooking = true;
}
void OnTriggerExit2D(Collider2D other)
{
isLooking = false;
}
I don’t know why but using Quaternion.Slerp I was able to do it but I still want to know why it works with mouse position but not with target position!!
please if anyone has time tested or explain it if posible thank you very much for help.