拖拽旋转团结

时间:2017-09-07 03:51:18

标签: c# unity3d rotation unity5

请通过拖动旋转对象需要帮助。物体是船的舵,随着触摸屏旋转。我有一个问题,点击对象总是返回角度0.然后,如果我可以让它旋转,但它总是从0开始,而不是从我留下的地方开始。

public void OnClick()
{
    Vector3 pos = Camera.main.WorldToScreenPoint(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;
}

public void OnDrag()
{
    Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
    pos = Input.mousePosition - pos;
    float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - baseAngle;
    transform.rotation = Quaternion.AngleAxis(ang, Vector3.right);
}

1 个答案:

答案 0 :(得分:1)

很抱歉,但上一篇文章不对。问题是您的多维数据集的“默认”方向(您使用Vector.right,但您需要Vector.up),以及它的错误轴。您可以使用“z”和“y”,而不是“y”和“z”。我现在修复它,结束完全重写我的答案。

private Vector2 GetDirectionToMouse()
{
    var mousePosition = Camera.main.WorldToScreenPoint(transform.position);
    Vector2 result = Input.mousePosition - mousePosition;
    return result;
}

float dragAngle;

public void OnBeginDrag(PointerEventData data)
{
    var directionToMouse = GetDirectionToMouse().normalized;
    var mouseAngle = Mathf.Atan2(directionToMouse.y, directionToMouse.x) * Mathf.Rad2Deg;
    var transAngle = Mathf.Atan2(transform.up.z, transform.up.y) * Mathf.Rad2Deg;
    dragAngle = mouseAngle - transAngle;
}    

public void OnDrag(PointerEventData data)
{
    var directionToMouse = GetDirectionToMouse().normalized;
    var mouseAngle = Mathf.Atan2(directionToMouse.y, directionToMouse.x) * Mathf.Rad2Deg;
    var targetAngle = mouseAngle - dragAngle;

    transform.rotation = Quaternion.AngleAxis(targetAngle, Vector3.right);
}