2016-07-24 102 views
0

我正在嘗試構建觸摸設備的2D遊戲。現在我正試圖在場景中投射一場對撞機來做一些事情。例如,如果點擊射線左鍵,則播放器向左移動。RaycastHit2D - 觸摸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 
    } 
    } 
    } 
    } 
} 

回答

0

說不上來,如果這幫助,但我是這樣做的:

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