2014-09-25 95 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到似乎是正确的值。