Unity LookAt,但将整个身体朝3D空间中的方向旋转

浪费了很多时间试图找出轮换方式,并花费了很多时间来寻找答案,但是找不到适合我问题的东西。我需要将整个gameObject旋转到特定方向,而不是沿y轴旋转:

Unity LookAt,但将整个身体朝3D空间中的方向旋转

1)在Quaternion.LookRotation或Atan2内给定方向的同时,当前对象如何旋转。 2,3)如何旋转的示例。红色ot键简化了旋转发生的枢轴点

除了旋转的gameObject转换和旋转gameObject的方向之外,没有太多代码可显示,因为没有太多代码。

根据要求

[System.Serializable]
public class ToRotate
{
    //Object which will be rotated by the angle
    public GameObject gameObject;
    //Object last known position of this object. The object is rotated towards it's last global position
    private Vector3 lastPosition;

    //Initializes starting world position values to avoid a strange jump at the start.
    public void Init()
    {
        if (gameObject == null)
            return;

        lastPosition = gameObject.transform.position;
    }

    //Method which updates the rotation
    public void UpdateRotation()
    {
        //In order to avoid errors when object given is null.
        if (gameObject == null)
            return;
        //If the objects didn't move last frame,no point in recalculating and having a direction of 0,0
        if (lastPosition == gameObject.transform.position)
            return;

        //direction the rotation must face
        Vector3 direction = (lastPosition - gameObject.transform.position).normalized;

        /* Code that modifies the rotation angle is written here */

        //y angle
        float angle = Mathf.Rad2Deg * Mathf.Atan2(direction.x,direction.z);

        Quaternion rotation = Quaternion.Euler(0,angle,0);
        gameObject.transform.rotation = rotation;

        lastPosition = gameObject.transform.position;
    }
}
h3251300 回答:Unity LookAt,但将整个身体朝3D空间中的方向旋转

由于您希望对象的 local down 指向计算的方向,同时尽可能保持对象的局部 right 不变,因此我将使用Vector3.Cross找到该 down right 的叉积,以确定对象的本地 forward 应当面对的方向,然后使用Quaternion.LookRotation获取相应的轮换:

//Method which updates the rotation
public void UpdateRotation()
{
    //In order to avoid errors when object given is null.
    if (gameObject == null)
        return;
    //If the objects didn't move last frame,no point in recalculating and having a direction of 0,0
    if (lastPosition == transform.position)
        return;

    //direction object's local down should face
    Vector3 downDir = (lastPosition - transform.position).normalized;

    // direction object's local right should face
    Vector3 rightDir = transform.right;

    // direction object's local forward should face
    Vector3 forwardDir = Vector3.Cross(downDir,rightDir);

    transform.rotation = Quaternion.LookRotation(forwardDir,-downDir);

    lastPosition = transform.position;
}
本文链接:https://www.f2er.com/3149865.html

大家都在问