2014-11-21 105 views
0

我正在尋找一個簡單的解決方案,沿觸摸手勢順時針/逆時針旋轉2d對象。unity2d沿z軸旋轉一個遊戲對象

這是我試過,但它不能正常工作

下面的代碼片段:

void OnMouseDown() 
{ 
    Vector3 pos = Camera.main.ScreenToWorldPoint(transform.position); 
    pos = Input.mousePosition - pos; 
    baseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg; 
    baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) * Mathf.Rad2Deg; 
} 

void OnMouseDrag() 
{ 
    Vector3 pos = Camera.main.ScreenToWorldPoint(transform.position); 
    pos = Input.mousePosition - pos; 
    float angle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - baseAngle; 
    transform.rotation = Quaternion.AngleAxis(angle, new Vector3(0, 0, 1)); 
} 
+0

你能告訴我們,它不能正常工作嗎? – maZZZu 2014-11-21 06:49:49

+0

它不夠光滑,其旋轉取決於放置哪個象限。 – Nikhil 2014-11-21 08:22:34

+0

你想如何輪換工作?當用戶拖動手指說左右旋轉時,你想旋轉對象嗎?或者物體應該朝向手指的方向嗎? – Smilediver 2014-11-22 01:21:40

回答

0

方式一:

Vector3 oldMousePos; 

void OnMouseDown() 
{ 
    oldMousePos = Input.mousePosition; 
} 

void OnMouseDrag() 
{ 
    Vector3 diff = Input.mousePosition - oldMousePos; 
    oldMousePos = Input.mousePosition; 
    float angle = diff.x * rotationSpeed; 
    transform.Rotate(Vector3.forward, angle); 
} 

另一種方式

void OnUpdate() 
{ 
    float angle = Input.GetAxis("Mouse X") * rotationSpeed; 
    transform.Rotate(Vector3.forward, angle); 
} 

你可以換Vector3.forward改變旋轉發生的軸。你可以調整rotationSpeed來改變旋轉多少物體。

0

單擊對象並拖動以將其旋轉到所需的方向。

using UnityEngine; 
using System.Collections; 

public class DragRotate : MonoBehaviour { 

    [Header("Degree of rotation offset. *360")] 
    public float offset = 180.0f; 

    Vector3 startDragDir; 
    Vector3 currentDragDir; 
    Quaternion initialRotation; 
    float angleFromStart; 

    void OnMouseDown(){ 

    startDragDir = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; 

    initialRotation = transform.rotation; 
    } 


    void OnMouseDrag(){ 
    Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; 

    difference.Normalize(); 


    float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg; 

    transform.rotation = Quaternion.Euler(0f, 0f, rotationZ - (90 + offset)); 
    } 
}