Search code examples
c#unity-game-enginerotationgameobject

I need to rotate a gameObject towards another gameobject in Unity with c#, but i want the rotation to be only in z


I have done this program but when i move my gameobject(the seccond one) the rotation of the first gameObject in y starts to go randomly from 90 to -90.

public GameObject target; 
public float rotSpeed;  
void Update(){  
Vector3 dir = target.position - transform.position; 
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle));
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotSpeed * Time.deltaTime);
}

Solution

  • The simplest way for this is not going through Quaternion but Vector3 instead.

    What many people don't know is: You can not only read but also assign a value to e.g. transform.right which will adjust the rotation in order to make the transform.right match with the given direction!

    So what you can do is e.g.

    public Transform target; 
    public float rotSpeed;  
    
    void Update()
    {  
        // erase any position difference in the Z axis
        // direction will be a flat vector in the global XY plane without depth information
        Vector2 targetDirection = target.position - transform.position;
    
        // Now use Lerp as you did
        transform.right = Vector3.Lerp(transform.right, targetDirection, rotationSpeed * Time.deltaTime);
    }
    

    If you need this in local space since e.g. your object has a default rotation on Y or X you can adjust this using

    public Transform target; 
    public float rotSpeed;  
    
    void Update()
    {  
        // Take the local offset
        // erase any position difference in the Z axis of that one
        // direction will be a vector in the LOCAL XY plane
        Vector2 localTargetDirection = transform.InverseTransformDirection(target.position);
    
        // after erasing the local Z delta convert it back to a global vector
        var targetDirection = transform.TransformDirection(localTargetDirection);
    
        // Now use Lerp as you did
        transform.right = Vector3.Lerp(transform.right, targetDirection, rotationSpeed * Time.deltaTime);
    }