# How can I make a sprite object rotate to face another object using angularVelocity?

How can I make a sprite object rotate to face another object using angularVelocity?

The game I’m working on is a platformer that uses a lot of physics.I am trying to make an enemy that will rotate to face my player and lunge at him. Though what ends up happening is that the enemy continuously turns to the left regardless of where my player is.

The code in question is below.

``````Quaternion rotation = Quaternion.LookRotation
(transform.position - target.position, transform.TransformDirection(Vector3.up));
if(transform.rotation .z > rotation.z)
{
rigidbody2D.angularVelocity = targetingVelocity;
}
else if (transform.rotation .z < rotation.z)
{
rigidbody2D.angularVelocity = targetingVelocity * -1;
}
``````

So what the code is suppose to do is find the angle that is directly facing the target and if its rotation is greater then it rotates down to face it and vice versa. I want to have every action controlled by physics and I have found ways to do this without physics. I just want to see if anyone knows a way I can make this work.

if anybody wants to look at the whole code I’ve attached it below

``````using UnityEngine;
using System.Collections;

public class springEnemy : MonoBehaviour {

public float attackTimer;
public float maxAttackTimer;
public Transform target;
public float targetingVelocity;
public float springPower;

// Use this for initialization
void Start () {
attackTimer = maxAttackTimer;
}

// Update is called once per frame
void Update () {
if(attackTimer < (maxAttackTimer/2))
{
attackTimer = maxAttackTimer;
rigidbody2D.AddForce(transform.right * springPower * rigidbody2D.mass);
}
else
{
attackTimer -= Time.deltaTime;
}
Vector3 theScale = transform.localScale;
theScale.x = (attackTimer / maxAttackTimer);
transform.localScale = theScale;
if(target)
{
Quaternion rotation = Quaternion.LookRotation
(transform.position - target.position, transform.TransformDirection(Vector3.up));
transform.localRotation = new Quaternion(0,0,rotation.z,rotation.w);
/*if(transform.rotation.z > rotation.z)
{
rigidbody2D.angularVelocity = targetingVelocity;
}
else if (transform.rotation.z < rotation.z)
{
rigidbody2D.angularVelocity = targetingVelocity * -1;
}*/
}
}
}
``````

“if(transform.rotation .z > rotation.z)”

You can’t use Quaternions like that I’m afraid, you seem to be trying to use them like Euler angles, and they are different.

I think what you need is Quaternion Lerp to gradually move the rotation to follow the direction of the player: Unity - Scripting API: Quaternion.Lerp