如何让玩家停止unity 2d中的无限跳跃

How to make player stop infinite jump in unity 2d

所以我刚接触 unity 才 2 天,我遇到了我的播放器在空中跳跃的问题。我可以继续点击空格键,我的玩家将继续跳跃而不是停止,我正在努力让玩家只能在地面而不是空中跳跃。我一直在尝试很多教程,其中大部分只是让我的游戏冻结并且不再工作。我也一直在尝试找出如何使用地面检查,但我仍然不确定该怎么做。

这是我知道的代码。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PM : MonoBehaviour
{
    public float moveSpeed;
    public float jumpHeight;
    Rigidbody2D rb;


    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update() {
    float moveDir = Input.GetAxis("Horizontal") * moveSpeed;
    rb.velocity = new Vector2(moveDir, rb.velocity.y);

    // Your jump code:
    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
    }
   }
}

是的,您确实需要进行某种地面检查。网上有很多很好的教程,例如,https://www.youtube.com/watch?v=c3iEl5AwUF8&t=17s(“Unity 中进行地面检查的 3 种方法”)。

要实现简单的“光线向下检查”,您需要为 ground/platforms 分配一个与玩家图层不同的图层蒙版。在这个例子中,我添加了一个名为“Ground”的新层。

然后您可以使用这个简单的代码进行测试。

BoxCollider2D boxColliderPlayer;
int layerMaskGround;
float heightTestPlayer;

void Start()
{
    rb = GetComponent<Rigidbody2D>();

    // Get the player's collider so we can calculate the height of the character.
    boxColliderPlayer = GetComponent<BoxCollider2D>();
    // We do the height test from the center of the player, so we should only check
    // halft the height of the player + some extra to ignore rounding off errors.
    heightTestPlayer = boxColliderPlayer.bounds.extents.y + 0.05f;
    // We are only interested to get colliders on the ground layer. If we would
    // like to jump ontop of enemies we should add their layer too (which then of
    // course can't be on the same layer as the player).
    layerMaskGround = LayerMask.GetMask("Ground");
}

void Update()
{
    float moveDir = Input.GetAxis("Horizontal") * moveSpeed;
    rb.velocity = new Vector2(moveDir, rb.velocity.y);

    // Your jump code:
    if (Input.GetKeyDown(KeyCode.Space) && IsGrounded() )
    {
        rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
    }
}


/// <summary>
/// Simple check to see if our character is no the ground. 
/// </summary>
/// <returns>Returns <c>true</c> if the character is grounded.</returns>
private bool IsGrounded()
{
    // Note that we only check for colliders on the Ground layer (we don't want to hit ourself). 
    RaycastHit2D hit = Physics2D.Raycast(boxColliderPlayer.bounds.center, Vector2.down, heightTestPlayer, layerMaskGround);
    bool isGrounded = hit.collider != null;
    // It is soo easy to make misstakes so do a lot of Debug.DrawRay calls when working with colliders...
    Debug.DrawRay(boxColliderPlayer.bounds.center, Vector2.down * heightTestPlayer, isGrounded ? Color.green : Color.red, 0.5f);
    return isGrounded;
}

如您所见,我希望玩家角色有一个 BoxCollider2D - 我想您已经有了,否则角色会掉到地上)。当你在做 2D 的东西时要小心,不要混合普通的 3D 碰撞器。