2015-04-05 103 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