2016-08-13 85 views
0

我是新來的Unity和開發移動2D遊戲,現在我能夠使對象左右移動,當我在屏幕中心之前或之後觸摸屏幕。但是我想要觸摸物體並在x軸上拖動它,同時我的手指仍然觸摸屏幕並移動,所以我希望物體位於我手指的同一個x位置,任何人都可以幫助我如何操作它正確: 這裏是如果我在屏幕中心之前或之後感動我如何移動對象的代碼:團結遊戲拖動對象與手指運動

public class paddle : MonoBehaviour { 

    public Rigidbody2D rb; 
    public float speed; 
    public float maxX; 
    bool currentisAndroid=false; 
    // Use this for initialization 
    void Start() { 
     rb = GetComponent<Rigidbody2D>(); 
     #if UNITY_ANDROID 
     currentisAndroid=true; 
     #else 
     currentisAndroid=false; 
     #endif 
    } 

    // Update is called once per frame 
    void Update() { 
     if (currentisAndroid == true) { 
      if (Input.GetTouch (0).position.x < Screen.width/2 && Input.GetTouch (0).phase == TouchPhase.Stationary) 
       moveLeft(); 
      else if (Input.GetTouch (0).position.x > Screen.width/2 && Input.GetTouch (0).phase == TouchPhase.Stationary) 
       moveRight(); 
      else 
       stop(); 

     } else { 
      float x = Input.GetAxis ("Horizontal"); 
      //if (Input.GetTouch (0).position.x == rb.position.x && Input.GetTouch (0).phase == TouchPhase.Moved) 
      if (x == 0) 
       stop(); 
      if (x < 0) 
       moveLeft(); 
      if (x > 0) 
       moveRight(); 

      Vector2 pos = transform.position; 
      pos.x=Mathf.Clamp (pos.x,-maxX,maxX); 
      transform.position = pos; 
     } 


    } 
    void moveLeft() 
    { 
     rb.velocity = new Vector2 (-speed, 0); 
    } 
    void moveRight() 
    { 
     rb.velocity = new Vector2 (speed, 0); 
    } 
    void stop() 
    { 
     rb.velocity = new Vector2 (0, 0); 
    } 
    public float getposition() 
    { 
     return rb.position.y; 
    } 
} 

回答

0

最簡單的方法:

添加成分DragRigidbody腳本,你就可以通過鼠標或觸摸屏觸摸拖動對象。

0

如果我理解正確:
1 - 光線投射距離手指位置垂直相機成現場。
2 - 選擇命中對象。
3 - 將您的相機映射到世界座標,並根據您的射線與地圖或遊戲對象\對象的命中點移動該對象。

  • Physics.Raycast();
  • RaycastHit.collider(); Camera.main.ScreenToWorldPoint(Input.GetTouch(< 0或1或all>)。position);}};}};}};

如果你想在地圖上移動物體,你可以跟蹤你的觸摸,以及當它接近角落時移動相機的直接(水平 - 垂直)。