对象不会从其上一个位置

时间:2015-12-06 20:10:32

标签: c# unity3d

所以我有一个物体,旋转得很好。但是,这是一个单击并拖动旋转。每当我将它旋转到一个位置时,它就会停留在那里,但是当我再次尝试旋转它时,它会从起点旋转,而不是从它离开的地方旋转。这是我的代码:

using UnityEngine;
using System.Collections;

public class Basket_Script : MonoBehaviour 
{
     private float baseAngle = 0.0f;

     void OnMouseDown() 
     {
         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;
     }

     void OnMouseDrag()
     {
         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.down);
     }
} 

我有点像菜鸟,我有点复制了这个代码并修改了它。

1 个答案:

答案 0 :(得分:0)

问题是你总是在旋转开始之前设置transform.rotation值完全忽略它的初始值,所以它每次从相同的起点旋转。简单的解决方案是保存鼠标按下的值,并将其应用于鼠标拖动时的整体旋转,如下所示:

using UnityEngine;
using System.Collections;

public class Basket_Script : MonoBehaviour 
{
    private float baseAngle = 0.0f;
    private Quaternion startRotation = Quaternion.identity;

    void OnMouseDown() 
    {
        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;
        // Remember the value
        startRotation = transform.rotation;
    }

    void OnMouseDrag()
    {
        Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
        pos = Input.mousePosition - pos;
        float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - baseAngle;
        // Multiply desired rotation by starting rotation
        transform.rotation = Quaternion.AngleAxis(ang, Vector3.down) * startRotation;
    }
} 

希望这有帮助。