RaycastHit2D-触摸2D游戏

本文关键字:游戏 2D 触摸 RaycastHit2D- | 更新日期: 2023-09-27 17:58:19

我正在尝试为触摸设备构建一个2D游戏。现在,我正试图向场景中的对撞机投射光线来做一些事情。例如,如果光线击中左侧按钮,玩家将向左移动。

我在谷歌和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
     }
    }
   }
  }
 }

RaycastHit2D-触摸2D游戏

不知道这是否有帮助,但我就是这样做的:

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