首页 > 解决方案 > 如何使用 c# 在 Unity 中避免 MidAir 跳跃

问题描述

我想创建一个跳跃脚本,到目前为止,问题是我不希望游戏对象在空中跳跃

我尝试将 OnCollisionStay/Enter 与 OnCollisionExit 一起使用来生成一个布尔值,该布尔值在跳跃前与 Input 一起检查,这效果最好,但统一缺少触发器

我无法使用 gameObject.transform.position.y 检查位置,因为我有不同的提升平台。

isGrounded 使用不同的代码,但它会干扰我的其他动作(由 AddForce 在 Input 上实现)

我无法理解为什么这段代码不起作用,我希望有人能帮助我理解。

using UnityEngine
public class PlayerMovement : MonoBehaviour
{
    private CharacterController controller;
    public Rigidbody rb;
    public Transform PPos; 
    public float jumpForce = 10f;
}
    public void Update()
{

    if(controller.isGrounded && Input.GetKeyDown(KeyCode.Space))
    {
      rb.AddForce(0, jumpForce, 0);
      Debug.Log("Jump Executed");
    }
}

我没有收到语法错误

标签: c#unity3d

解决方案


编辑

controller.isGrounded每当您的角色有能力跳跃时,您都需要设置。

玩家脚本

void OnCollisionEnter(collision other)
{
    controller.isGrounded = other.gameObject.CompareTag("Ground");
}

原来的

如果你想在半空中跳跃,你将不得不移除你的角色控制器在地面上的条件。

if(Input.GetKeyDown(KeyCode.Space))

推荐阅读