我正在做我的第一场比赛,现在我遇到一个问题:当我按下它时,我有一个跳跃按钮,我在跳跃,但是当我在空中时,我可以再次按下它并再次在空中跳跃。如何解决该问题,所以我只能跳到地面上。这是我的代码:
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
}
这里是代码
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();
}
}
}
首先,您需要一个布尔值(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();
}