[英]Rotate 3D Object with finger touch Unity 3D
I want to rotate a ball when swiping left & right anywhere on the screen, so I made the script bellow, but the ball is rotating only when I swipe directly on the ball not anywhere on the screen, do you have any idea? 我想在屏幕上向左或向右滑动时旋转球,所以我将脚本放到下面,但是只有当我直接在球上滑动而不在屏幕上的任何地方时,球才旋转。
Ball Script: 球形脚本:
private float baseAngle = 0.0f;
public Camera cam;
void OnMouseDown()
{
Vector3 pos = cam.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 = cam.WorldToScreenPoint(transform.position);
pos = Input.mousePosition - pos;
float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - baseAngle;
transform.rotation = Quaternion.AngleAxis(-ang, Vector3.up);
}
Your trouble is that the script you provided is attached to the ball itself, so touches (clicks) are processed only by the ball. 您的麻烦是您提供的脚本已附加到球本身,因此触摸(单击)仅由球处理。 In other word methods OnMouseDown
and OnMouseDrag
are called only when the touch(click) hits the ball. 换句话说,仅在touch(click)击中球时才调用OnMouseDown
和OnMouseDrag
方法。 See the Documentation . 请参阅文档 。 It says: 它说:
OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider. 当用户在GUIElement或Collider上方按下鼠标按钮时,将调用OnMouseDown。
There are at least to ways to get what you want: 至少有一些方法可以获取您想要的东西:
Input
class instead of OnMouseDown
and OnMouseDrag
. 使用Input
类中的方法,而不是OnMouseDown
和OnMouseDrag
。 For example Input.GetMouseButton - it is called every time user click mouse button ( or touch) no matter, what click hit. 例如Input.GetMouseButton-每当用户单击鼠标按钮(或触摸)时,无论单击什么,它都会被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.