RaycastHit2D - 触摸2D游戏

时间:2016-07-24 11:20:31

标签: c# android ios unity3d touch

我正在尝试为触控设备制作2D游戏。现在我正试图在场景中投射射线对抗碰撞器来做某事。例如,如果点击光线击中左按钮,则播放器向左移动。

我在google和youtube的各个地方搜索过,但还没有想到如何做到这一点。我是Unity和编程的新手,但从我搜索过的内容来看,如果我想在2D屏幕上检测触摸比3D游戏更复杂!!!

void Update () 
{
 if (Input.touchCount > 0 )
 {
  for ( int i = 0; i < Input.touchCount; i++)
  { 
   if ( Input.GetTouch(i).phase == TouchPhase.Began)
   {
    Ray2D ray = Camera.main.ScreenToWorldPoint (Input.GetTouch(i).position);
    RaycastHit2D hit;

    if ( Physics2D.Raycast ( ray, out hit) ) )
    {
     if (hit.transform.gameobject.name == "left")
     {
      // Do Something
     }
    }
   }
  }
 }

1 个答案:

答案 0 :(得分:0)

Dunno如果有这个帮助,但我就是这样做的:

//Get current worldspace position of mouse cursor
    RaycastHit2D[] hits = Physics2D.LinecastAll(clickedPos,clickedPos,theLayer);

    // Copy Linecast to HashSet (unique records), clean out the "Background" GameObject
    foreach (RaycastHit2D arf2D in hits) {
        //linecast_GameObject = GameObject.FindWithTag(arf2D.collider.tag);
        linecast_GameObject = GameObject.Find(arf2D.collider.name);

        //if (linecast_GameObject.name != "Background") {
        if (linecast_GameObject.tag != "Background") {
            linecast_GameObject_HashSet.Add(linecast_GameObject);
            clickedOnTheBackground = false;
        }
        else if (hits.Length == 1) {
            clickedOnTheBackground = true;
            fingerSelection_GO = GameObject.FindWithTag("Dummy_GameObject");
            //fingerSelection_GO = GameObject.Find("Dummy_GameObject");
        }
    }
相关问题