2014-11-21 78 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)); 
    } 
}