在unity中用鼠標控制控制物體旋轉

功能大概是這個樣子的,用鼠標的上下、左右移動來控制unity中某個物體的左右、上下轉轉。

    public  Camera cam;
    void Update()
    {
        Vector3 fwd = cam.transform.forward;
        fwd.Normalize();
        if (Input.GetMouseButton(0))
        {
            Vector3 vaxis = Vector3.Cross(fwd, Vector3.right);
            transform.Rotate(vaxis, -Input.GetAxis("Mouse X"), Space.World);
            Vector3 haxis = Vector3.Cross(fwd, Vector3.up);
            transform.Rotate(haxis, -Input.GetAxis("Mouse Y"), Space.World);
        }
    }

transform.Rotate()這個函數官方是這樣解釋的:

public void Rotate(Vector3 axis, float angle, Space relativeTo = Space.Self); 
axis           Axis to apply rotation to.
angle          Degrees to rotation to apply.
relativeTo     Rotation is local to object or World.

因為物體在不斷隨著鼠標的運動旋轉,所以旋轉時一定要在世界坐標中,否則我們看到的是物體繞著自身的軸轉轉。另外,我們看到的都是通過camera來看到的,所以Rotate的第一個參數axis一定要是camera的某個軸向,左右方向的旋轉需要繞著camera的up方向,上下方向的旋轉需要繞著camera的right方向。
這樣無論物體和camera初始的rotation是多少,都可以正確的實現旋轉啦。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容