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);