简体   繁体   中英

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);
}

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 eg 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 eg

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 eg 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM