【发布时间】:2016-01-27 00:40:58
【问题描述】:
你好!
我目前正在开发 Unity 引擎中的 2D 平台游戏,我在其中创建了一个可以进行双跳的角色。
一开始一切都很好,但我现在意识到有一个破坏游戏的错误使他能够进行第三次跳跃(出于某种原因)。我不能为了它找出问题所在。
PlayerController.cs
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
/*
TODO: Find out why the character ocationally
gets 3 jumps instead of 2.
I think it's the "isGrounded" that returns
a false posetive.
*/
[Header("Ground Recognition")]
public BoxCollider2D groundCollider;
public LayerMask groundAbles;
[Header("Audio")]
public GameObject jumpSound = null;
[Header("Visual")]
public GameObject jumpEffect = null;
float speed = 5f;
int maxJumps = 2;
int currentJumps = 0;
bool isGrounded = false;
float boundsLength = 0;
Vector3 movement;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update() {
CheckGroundCollision();
JumpLogic();
movement = new Vector3(Input.GetAxis("Horizontal") * speed, 0, 0);
movement *= Time.deltaTime;
transform.position += movement;
CheckGroundCollision();
}
void CheckGroundCollision()
{
isGrounded = groundCollider.IsTouchingLayers(groundAbles);
}
void JumpLogic()
{
if (isGrounded)
currentJumps = 0;
if (Input.GetButtonDown("Jump") && currentJumps < maxJumps)
{
GameObject newJumpSound = (GameObject)GameObject.Instantiate(jumpSound, (Vector2)transform.position, transform.rotation);
GameObject newJumpEffect = (GameObject)GameObject.Instantiate(jumpEffect, (Vector2)transform.position - new Vector2(0, 0.25f), transform.rotation);
GameObject.Destroy(newJumpEffect, 0.2f);
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, 0);
GetComponent<Rigidbody2D>().AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
currentJumps++;
CheckGroundCollision();
}
}
}
感谢所有帮助!
【问题讨论】:
-
只是作为一个测试,尝试将maxjumps设置为1。看看你是否可以获得2次跳跃。这可能是操作顺序问题,在按下跳转后但在与地面保持接触之前,您会得到 isGrounded = true。
-
你能在它运行时调试或打印一些信息吗?我很好奇
isGrounded是否会导致任何问题并过早重置currentJumps。 -
我已经测试了理论,问题确实是基于 currentJumps 被过早重置!
标签: c# unity3d 2d controllers unity5