Rotate relative to camera position.

Rotate relative to camera position.

物件以相對現在角度的方式 Rotate, X 軸 及 Y 軸

#define CalculateAngle  
// Calculate the angle relative to camera viewport  
using UnityEngine;  
using System.Collections;  
  
public class RotateCube : MonoBehaviour  
{  
    public float speed = 10f;  
    public bool flipX = false, flipY = false;  
    private Vector3 lastPosition;  
#if CalculateAngle  
    public Camera camera;  
    void Awake()  
    {  
        camera = (camera == null) ? Camera.main : camera;  
    }  
#endif  
  
    void OnMouseDown()  
    {  
        lastPosition = Input.mousePosition;  
    }  
    void OnMouseDrag()  
    {  
        Vector3 diff = -speed * Time.deltaTime * (Input.mousePosition - lastPosition);  
        diff = new Vector3((flipY?diff.y:-diff.y),(flipX?diff.x:-diff.x), 0f);  
#if !CalculateAngle  
        transform.Rotate(diff, Space.World);  
#else  
        Vector3 objUp = transform.InverseTransformDirection(camera.transform.TransformDirection(Vector3.up));  
        Vector3 objRight = transform.InverseTransformDirection(camera.transform.TransformDirection(Vector3.right));  
        transform.rotation *= Quaternion.AngleAxis(diff.y, objUp) * Quaternion.AngleAxis(diff.x, objRight);  
#endif  
        lastPosition = Input.mousePosition;  
    }  
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料