修正悬空(Unity2D)

问题描述 投票:-1回答:2

我正在做我的第一场比赛,现在我遇到一个问题:当我按下它时,我有一个跳跃按钮,我在跳跃,但是当我在空中时,我可以再次按下它并再次在空中跳跃。如何解决该问题,所以我只能跳到地面上。这是我的代码:

using UnityEngine;
using System.Collections;
using UnityStandardAssets.CrossPlatformInput;
public class Move2D : MonoBehaviour
{

    public float speed = 5f;
    public float jumpSpeed = 8f;
    private float movement = 0f;
    private Rigidbody2D rigidBody;

    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();


    }

    public void Jump()
    {

        rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
    }

    // Update is called once per frame

}
c# unity3d
2个回答
0
投票

这里是代码

public class Move2D : MonoBehaviour
{
    public bool isGrounded = false;
    public float speed = 5f;
    public float jumpSpeed = 8f;
    private float movement = 0f;
    private Rigidbody2D rigidBody;

    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();


    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "Ground") //you need to add a tag to your Ground, like "Ground"
        {
            isGrounded = true;
        }
    }
    public void Jump()
    {

        rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
        isGrounded = false;
    }
     void Update()
    {
        if (Input.GetButtonDown("Jump") && isGrounded == true)
        {
            isGrounded = false;
            Jump();
        }
    }
}

0
投票

首先,您需要一个布尔值(isGrounded)。然后,您必须使用

检查播放器与地面之间的碰撞
private void OnCollisionEnter2D(Collision2D other)
{
    if(other.gameObject.tag == "Ground") //you need to add a tag to your Ground, like "Ground"
    {
       isGrounded = true;
    }
}

然后在Update方法中添加以下代码:

if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
    {
        isGrounded = false;
        Jump();
    }
© www.soinside.com 2019 - 2024. All rights reserved.