简体   繁体   English

用手指触摸旋转3D对象Unity 3D

[英]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)击中球时才调用OnMouseDownOnMouseDrag方法。 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: 至少有一些方法可以获取您想要的东西:

  • If you want to get touched everywhere on the screen create a separate gameobject (empty and containing only a collider and your script) and make it collider Bounds fit the screen. 如果您想在屏幕上的任何地方都受到触摸,请创建一个单独的游戏对象(空并且仅包含对撞机和您的脚本),并将其设置为适合屏幕的对撞机边界。 Then add a public transform field to your script and assign the ball's transform to make it possible to rotate ball from the other script 然后将公共转换字段添加到脚本中,并指定球的转换,从而可以从其他脚本旋转球
  • Use methods from Input class instead of OnMouseDown and OnMouseDrag . 使用Input类中的方法,而不是OnMouseDownOnMouseDrag 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM