我想创建一个游戏,我可以在其中左右移动框以避免掉落盒子并且它可以工作,但问题是当我将手指放在一个地方时,然后播放器盒左右摇动。你可以在这个gif http://gfycat.com/FragrantBrokenEyas看到这个。这里是C#脚本的代码
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);
答案 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
调整为正确的值即可。