2015-04-05 100 views
0

我想要改变我的Android游戏,它就像pong。我希望能够在手机上拖动桨。提前感谢您的帮助。这是我最早的代码:Unity 2D使用拖动来上下移动

using UnityEngine; 
using System.Collections; 

public class MoveRacket : MonoBehaviour { 
     public float speed = 30; 
     public string axis = "Vertical"; 

     void FixedUpdate() { 
     float v = Input.GetAxisRaw (axis); 
      GetComponent<Rigidbody2D>().velocity = new Vector2 (0, v) * speed; 



    } 
} 

继承人我的旧代码,但它仍然无法正常工作。

using UnityEngine; 
using System.Collections; 

public class MoveRacket : MonoBehaviour { 
    public float speed = 30; 
    public string axis = "Vertical"; 
    public object racket = "Racket"; 
    public bool touchInput = true; 
    public Vector2 touchPos; 





    void FixedUpdate() { 

     //used to not have anything in parentheses 
     float v = Input.GetAxisRaw (axis); 
     //GetComponent<Rigidbody2D>().velocity = new Vector2 (0, v) * speed; 
     if (Input.touchCount == 1) 
     { 
      Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); 
      Vector2 touchPos = new Vector2(wp.x, wp.y); 
      if (racket == Physics2D.OverlapPoint(touchPos)); 
      { 
       GetComponent<Rigidbody2D>().velocity = new Vector2 (0, v) * speed; 

      } 
     } 
    } 
} 

继承人我现在的代码已经修复。

using UnityEngine; 
using System.Collections; 

public class MoveRacket : MonoBehaviour { 
    public float speed = 30; 
    public string axis = "Vertical"; 
    public object racket = "Racket"; 
    public bool touchInput = true; 
    public Vector2 touchPos; 





    void FixedUpdate() { 

     //used to not have anything in parentheses 
     //float v = Input.GetAxisRaw (axis); 
     float v = Input.GetAxisRaw (axis); 
     GetComponent<Rigidbody2D>().velocity = new Vector2 (0, v) * speed; 
     if (Input.touchCount == 1) 
     { 
      Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position); 
      Vector2 touchPos = new Vector2(wp.x, wp.y); 
      if (Racket.Collider2D == Physics2D.OverlapPoint(touchPos)); 
      { 
       this.transform.position.y = wp.y 

      } 
     } 
    } 
} 

答案:上面的代码是固定的,应该可用。

回答

2

你在说你想拖动,因此你需要触摸 首先,你需要检查触摸,如果用户触摸屏幕然后raycast2d检查他是否触摸桨,并使用相同的逻辑将它保持在您用作鼠标的手指位置。

首先尝试一下,用这个提示 http://answers.unity3d.com/questions/577314/how-to-detect-if-a-sprite-was-object-was-touched-i.html

谢谢

+0

感谢,我会尝试一下,一旦我有我的电脑和我在一起。 – 2015-04-06 13:47:43

+0

我现在可以使用你的帮助。我已经尝试过自己,但我不知道什么与我有关,考虑到我只是在移动y,而且如果您有一些时间我想要帮助解决我的错误,我会出错。提前致谢 – 2015-04-06 21:30:17

+1

好吧,不要使用刚体组件,只需在你的第二条语句中使用这个: this.transform.position = new vector3(wp.x,wp.y,0); 现在确定如果你不想要y位置改变,然后使用this.tranform.position.y而不是wp.y 告诉我错误并告诉我触摸是否正常工作? – LumbusterTick 2015-04-07 05:54:10