为什么当玩家在空中按空格键跳跃时,再按空格键他又跳得更高了?


public bool useCharacterForward = false;
public bool lockToCameraForward = false;
public float turnSpeed = 10f;
public KeyCode sprintJoystick = KeyCode.JoystickButton2;
public KeyCode sprintKeyboard = KeyCode.Space;
public bool useJump = false;
public Vector3 jump;
public float jumpImpulse;
private float turnSpeedMultiplier;
private float speed = 0f;
private float direction = 0f;
private bool isSprinting = false;
private Animator anim;
private Vector3 targetDirection;
private Vector2 input;
private Quaternion freeRotation;
private Camera mainCamera;
private float velocity;
private bool isGrounded;
private Rigidbody rb;
// Use this for initialization
void Start()
{
anim = GetComponent<Animator>();
mainCamera = Camera.main;
rb = GetComponent<Rigidbody>();
jump = new Vector3(0.0f, 2.0f, 0.0f);
}
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.tag == "Ground")
{
isGrounded = true;
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && useJump)
{
rb.AddForce(jump * jumpImpulse, ForceMode.Impulse);
isGrounded = false;
}
}

即使玩家在空中,即使我在检查地面标签,我仍然可以在玩家跳跃后在空中再次按空格键,它将使玩家跳跃并使玩家在空中更高。

但是我将isGround设置为false,玩家离地面更高,仍然按空格键,使它在空中跳跃,而已经在空中了。

这个截图显示了地面对象是如何在层次结构中构建的。玩家有一个胶囊碰撞器和一个刚体。

有3个地板对象:

地板例子

物理(刚体)仅在FixedUpdate中更新。在每个对撞机的FixedUpdate循环中也调用OnCollisionStay

在你的设置中,在你第一次按下OnCollisionStay并将isGrounded再次设置为true后,有一点机会再次被触发,允许你以后再跳一次。

我认为它已经可以防止这种情况,如果你移动到FixedUpdate甚至OnCollisonStay本身:

private bool isJump;
private bool isGrounded;
private void OnCollisionStay(Collision collision)
{
// In general rather use CompareTag instead of ==
// It causes an error If the tag is non-existent or has a typo making 
// your debugging way easier and is also slightly more efficient
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = true;
}
}
private FixedUdpate()
{
// Should we jump?
if(isJump && isGrounded)
{
rb.AddForce(jump * jumpImpulse, ForceMode.Impulse); 
isGrounded = false;
}
isJump = false;
}
private void Update()
{
// As you already did correctly get single event user input in Update
// in order to not miss one
// I would check the cheaper bool flag first
if (isGrounded && useJump && Input.GetKeyDown(KeyCode.Space))
{             
isJump = true;
}
}

现在应该确保跳跃只能在与地面碰撞时应用

最新更新