我在Win 64位机器上使用Unity 5.1.1,比运行我所创造的游戏更有能力。在制作2D横向卷轴游戏的过程中,我发现我的角色有时不会在提示时跳跃。下面是代码:
public float speed;
public float MomentAcc;
private float moveVertical;
private float score;
private float scoreP;
public GameObject wallRight;
public GUIText scoreText;
public bool touching;
void Start() {
MomentAcc = 10;
score = 0;
}
//Jump limiter
void OnCollisionStay2D() {
touching = true;
}
void OnCollisionExit2D() {
touching = false;
}
void Update() {
if (Input.GetKeyDown(KeyCode.W) && touching == true || Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began && touching == true) {
moveVertical = 29;
} else {
moveVertical = 0;
}
}
void FixedUpdate () {
scoreP = GameObject.Find ("Ball").GetComponent<Rigidbody2D> ().position.x + 11;
if(scoreP > score) {
score = score + 10;
}
UpdateScore ();
if(GetComponent<Death>().startGame == true) {
float moveHorizontal = 5;
Vector2 forward = new Vector2 (moveHorizontal, 0);
Vector2 jump = new Vector2 (0, moveVertical);
//Maxspeed limit
GetComponent<Rigidbody2D> ().AddForce (moveVertical * jump);
speed = moveHorizontal * MomentAcc * Time.deltaTime * 5;
if (GetComponent<Rigidbody2D> ().velocity.x < 7.000000) {
GetComponent<Rigidbody2D> ().AddForce (Vector2.right * speed);
if(GameObject.Find ("wallRight").GetComponent<wallRightScript>().wallJumpRight == true) {
GetComponent<Rigidbody2D> ().AddForce (new Vector2 (-420, 300));
}
if(GameObject.Find ("wallLeft").GetComponent<wallLeftScript>().wallJumpLeft == true) {
GetComponent<Rigidbody2D> ().AddForce (new Vector2(420, 150));
}
}
}
}
void UpdateScore() {
scoreText.text = "Score: " + (score );
}
}
(注:wallLeft/wallRight用于walljump)
这就是你的问题!
在这种情况下,您使用的是Input.GetKeyDown(KeyCode.W) && touching == true
,您的跳跃取决于touching
变量,当您按下"W"键时,该变量可能为假。你正在使用rigidbody
,你不能期望它总是与地面碰撞,当它被拖在水平。因此,您可能需要更改地面检查的实现。
这个教程是很好的学习2D字符。
还有一个建议!尝试将对象/组件的引用存储在一些变量中,以便于访问它们。在Update()/FixedUpdate()
中使用GetComponent<>
/GameObject.Find()
是不有效的,所以不是一个好的做法。