沿z轴游戏对象的unity2d旋转

时间:2014-11-21 06:05:42

标签: unity3d rotation

我正在寻找一种在触摸手势上顺时针/逆时针沿z轴旋转2d物体的简单解决方案。

这是我尝试但不能正常工作

以下是代码段:

 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));
}

2 个答案:

答案 0 :(得分: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以更改对象应旋转的数量。

答案 1 :(得分: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));
  }
}