Unity按住左鍵旋轉物體,按住右鍵移動物體,移動端單指旋轉物體,雙指移動物體

功能比較簡單,直接上代碼吧:

public class ModelController : MonoBehaviour {
    public Transform obj;
    public Camera objCamera;//模型攝像機
	
	void Update () {
#if UNITY_IOS || UNITY_IPHONE || UNITY_ANDROID
        //單指旋轉物體
        if (Input.touchCount == 1 && obj != null) {
			obj.Rotate(Vector3.up, -Input.GetAxis("Mouse X") * 10, Space.World);
            obj.Rotate(Vector3.right, Input.GetAxis("Mouse Y") * 10, Space.World);
        }
        //雙指移動物體
        else if (Input.touchCount > 1 && obj != null) {
            Vector2 point;
            Vector3 targetScreenSpace = Camera.main.WorldToScreenPoint(obj.position);
            Touch t1 = Input.GetTouch(0);
            Touch t2 = Input.GetTouch(1);
            point = t2.position;//實時手指位置 
            if (t1.phase == TouchPhase.Moved && t2.phase == TouchPhase.Moved) {
                obj.position = objCamera.ScreenToWorldPoint(new Vector3(point.x,point.y, targetScreenSpace.z));
            }
        }
        #elif UNITY_EDITOR
        //按住左鍵旋轉物體
        if (Input.GetMouseButton(0) && obj != null){
            if (Input.GetMouseButton(0)) {
                obj.Rotate(Vector3.up, -Input.GetAxis("Mouse X") * 10, Space.World);
                obj.Rotate(Vector3.right, Input.GetAxis("Mouse Y") * 10, Space.World);
            }
        }
        //按住右鍵拖動物體
        else if (Input.GetMouseButton(1) && obj != null)
        {
            Vector3 targetScreenSpace = objCamera.WorldToScreenPoint(obj.position);//用於獲取物體的z軸座標(物體離相機距離不變)
            Vector3 point = Input.mousePosition;
            obj.position = objCamera.ScreenToWorldPoint(new Vector3(point.x, point.y, targetScreenSpace.z));
        }
        #endif
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章