2016-10-04 88 views
0

我想移動我的移動設備的觸摸對象,就像那個玩家可以觸摸屏幕上的任何地方並移動他/她的手指一樣,遊戲對象將隨着它移動,而不是移動觸摸位置。如何在Unity3D中用手指觸摸移動

這裏是我的腳本到目前爲止,我沒有

void Update() { 

    if (Input.touchCount > 0) 
    { 
     Touch _touch = Input.GetTouch(0); // screen has been touched, store the touch 

     if(_touch.phase == TouchPhase.Moved) // finger moved 
     { 
      //offset = Camera.main.ScreenToWorldPoint(new Vector3(_touch.position.x, _touch.position.y, theplayer.transform.position.z)) - theplayer.transform.position; 

      touchPos = Camera.main.ScreenToWorldPoint(new Vector3(_touch.position.x, _touch.position.y, theplayer.transform.position.z)); 

      theplayer.transform.position = Vector2.Lerp(theplayer.transform.position, touchPos, Time.deltaTime*5f); 

     } 
     else if(_touch.phase == TouchPhase.Ended){ 
      touchPos = Vector3.zero; 
      offset = Vector3.zero; 
     } 

    } 

} // end 

腳本幾乎工作,但問題是,當我在屏幕上觸摸遊戲對象移動手指的下方,所以我不能看到遊戲對象。我不想要這個,我想要觸摸屏幕上的任何地方,並用手指移動不移動到手指位置。

謝謝。

回答

1

我已經解決了這個問題,我自己這裏是解決方案代碼。

// Update is called once per frame 
    void Update() { 

     if (Input.touchCount > 0) 
     { 
      _touch = Input.GetTouch(0); // screen has been touched, store the touch 

      if(_touch.phase == TouchPhase.Began){ 
       isDragging = true; 

       offset = Camera.main.ScreenToWorldPoint(new Vector2(_touch.position.x, _touch.position.y)) - theplayer.transform.position; 

      } 
      else if(_touch.phase == TouchPhase.Ended){ 
       offset = Vector2.zero; 
       isDragging = false; 
      } 

     } 

     if(isDragging){ 
      Vector2 _dir = Camera.main.ScreenToWorldPoint(new Vector2(_touch.position.x, _touch.position.y)); 
      _dir = _dir - offset; 

      theplayer.transform.position = Vector2.Lerp(theplayer.transform.position, _dir, Time.deltaTime * speed); 

     } 


    } // end 
+0

這是不完整的腳本,你必須聲明一些變量,如速度,isDragging(bool類型) –

相關問題