【问题标题】:unity2d rotation of a gameobject along z axis游戏对象沿 z 轴的 unity2d 旋转
【发布时间】:2017-12-11 09:00:21
【问题描述】:

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

这是我尝试过的,但它不能正常工作

这里是代码 sn-p :

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

【问题讨论】:

  • 您能告诉我们,它是如何工作不正常的吗?
  • 它不够平滑,它的旋转取决于它放置在哪个象限。
  • 您希望如何进行轮换?当用户左右拖动手指时,你想旋转对象吗?还是应该让物体朝向手指的方向?
  • @Smilediver : 第一个概念.. 我的意思是如果我向左拖动手指,它应该逆时针和顺时针旋转以便向右拖动手指

标签: unity3d rotation


【解决方案1】:

一种方式:

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来改变物体应该旋转多少。

【讨论】:

    【解决方案2】:

    单击对象并拖动以将其旋转到您想要的方向。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多