首页 文章

RaycastHit2D - 触摸2D游戏

提问于
浏览
0

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

我在google和youtube的各个地方搜索过,但还没有想到如何做到这一点 . 我是团结和编程的新手,但从我搜索的内容来看,如果我想要在屏幕上检测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

    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");
            }
        }
    

相关问题