2014-09-25 94 views
0

我想創建一個遊戲,在其中我可以左右移動盒子以避免掉盒子和它的工作,但問題是當我將手指放在一個地方,玩家盒子然後晃動左和右。你可以在這個gif http://gfycat.com/FragrantBrokenEyas看到這個。而這裏的C#腳本的代碼Unity android 2d運動問題

using UnityEngine; 
using System.Collections; 

public class PlayerMovement : MonoBehaviour { 
private Camera m_cam; 
private float m_offsetRight = 1.0F; 
private float m_offsetLeft = 0.0F; 


void Awake() { 
    m_cam = Camera.main; 
} 


void Update() { 
    rigidbody2D.velocity = new Vector2(0 * 10, 0); 
    Move(); 
} 


void Move() { 
    if (Application.platform == RuntimePlatform.Android) { 
     Vector3 player_pos = m_cam.WorldToViewportPoint(rigidbody2D.position); 
     Vector3 touch_pos = new Vector3(Input.GetTouch(0).position.x, 0, 0); 

     touch_pos = Camera.main.ScreenToViewportPoint(touch_pos); 

     if(touch_pos.x > player_pos.x) 
      rigidbody2D.velocity = new Vector2(1 * 10, 0); 
     else if (touch_pos.x < player_pos.x) 
      rigidbody2D.velocity = new Vector2(-1 * 10, 0); 
    } 
    else{  
     Vector3 player_pos = m_cam.WorldToViewportPoint(rigidbody2D.position); 
     float h = Input.GetAxis ("Horizontal"); 

     if (h > 0 && player_pos.x < m_offsetRight) 
      rigidbody2D.velocity = new Vector2(h * 10, 0); 
     else if (h < 0 && player_pos.x > m_offsetLeft) 
      rigidbody2D.velocity = new Vector2(h * 10, 0); 
     else 
      rigidbody2D.velocity = new Vector2(0, rigidbody2D.velocity.y); 
    } 
} 


void OnTriggerEnter2D(Collider2D other) { 
    if (other.gameObject.name == "Enemy(Clone)") { 
     Destroy(other.gameObject); 
     GameSetUp.score -= 2; 
    } else if (other.gameObject.name == "Coin(Clone)") { 
     GameSetUp.score += 2; 
     Destroy(other.gameObject); 
    } 
} 

}

我覺得現在的問題是什麼地方在這裏:

touch_pos = Camera.main.ScreenToViewportPoint(touch_pos); 

     if(touch_pos.x > player_pos.x) 
      rigidbody2D.velocity = new Vector2(1 * 10, 0); 
     else if (touch_pos.x < player_pos.x) 
      rigidbody2D.velocity = new Vector2(-1 * 10, 0); 

回答

1

這個「一次到位」恐怕是其中x座標的地方觸摸與玩家框的x座標大致相同。

當您的手指按下該區域時,在第一幀touch_pos.x > player_pos.x爲真,並且速度設置爲正值。在下一個框架球員已經移動到正面方向,這一次是touch_pos.x < player_pos.x是真實的,速度設置爲負值。這導致搖動效應。爲了避免這種情況,你可以例如緩慢地增加和減小速度,而不是在一幀中將其完全改變爲相反。您可以通過更改您的代碼以這樣做:

touch_pos = Camera.main.ScreenToViewportPoint(touch_pos); 

    const float acceleration = 60.0f; 
    const float maxSpeed = 10.0f; 

    if(touch_pos.x > player_pos.x) 
     if(rigidbody2D.velocity.x < maxSpeed) 
      rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x + acceleration * Time.deltaTime, 0); 
     else 
      rigidbody2D.velocity = new Vector2(maxSpeed, 0); 
    else if (touch_pos.x < player_pos.x) 
     if(rigidbody2D.velocity.x > -maxSpeed) 
      rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x - acceleration * Time.deltaTime , 0); 
     else 
      rigidbody2D.velocity = new Vector2(-maxSpeed, 0); 

只需調整acceleration到似乎是正確的值。