在网上看到一个鼠标拖动旋转的功能实现
public void OnBeginDrag(PointerEventData data)
{
if (!isActive)
{
return;
}
isSpinning = true;
playerController.StopMoving();
// get the angle to the mouse position on down frame
Vector3 inputPosition = new Vector3(data.position.x, data.position.y, 0f);
directionToMouse = inputPosition - Camera.main.WorldToScreenPoint(pivot.position);
// store the angle to mouse pointer on down frame
previousAngleToMouse = Mathf.Atan2(directionToMouse.y, directionToMouse.x) * Mathf.Rad2Deg;
}
public void OnDrag(PointerEventData data)
{
if (isSpinning && Camera.main != null && pivot != null && isActive)
{
// get the angle to the current mouse position
Vector3 inputPosition = new Vector3(data.position.x, data.position.y, 0f);
directionToMouse = inputPosition - Camera.main.WorldToScreenPoint(pivot.position);
angleToMouse = Mathf.Atan2(directionToMouse.y, directionToMouse.x) * Mathf.Rad2Deg;
// if we have dragged a minimum threshold, rotate the target to follow the mouse movements around the pivot
// (left-handed coordinate system; positive rotations are clockwise)
if (directionToMouse.magnitude > minDragDist)
{
Vector3 newRotationVector = (previousAngleToMouse - angleToMouse) * axisDirection;
targetToSpin.Rotate(newRotationVector);
previousAngleToMouse = angleToMouse;
}
}
}
代码是在拖动开始时通过求鼠标点击位置与旋转支点的XY求tanY/X得到当前鼠标的角度,然后在拖动继续时求新的角度。我没有理解的地方是为什么使用原来的角度减去新的角度,旋转的时候角度不是在不断变大吗,这样的话传入Rotate的值就是一个负值,但游戏中旋转是正常的,并且不管怎么旋转始终是在0-359度之间。是我理解错误了吗?