Unity2D防止角色多次跳跃 [英] Unity2D preventing character from multi-jumping

查看:1129
本文介绍了Unity2D防止角色多次跳跃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的角色可以随您按(W或空格键)跳跃一样多.我读到可以用Raycast阻止它,但是我不知道该怎么做.这是我角色的代码(这是一个平台游戏):

My character can jump as much as you press ( W or space) I've read that you can prevent it with Raycast, but I don't understand how to do so. This is my character's code(this is a platformer game) :

private Rigidbody2D myRigidBody2D;
void Start () {

    myRigidBody2D = GetComponent<Rigidbody2D>();

}

private void Update()
{
    if (Input.GetButtonDown("Jump"))
    {
        myRigidBody2D.AddForce(new Vector2(0, jumpForce));
    }
}

推荐答案

我读到您可以使用Raycast阻止它

I've read that you can prevent it with Raycast

是的,可以,但是您很可能会遇到

Yes, you can but you will likely run into problems which can still be fixed.

执行此操作的最佳方法是使用布尔变量来检查角色是否接触地面.您可以在OnCollisionEnter2DOnCollisionExit2D函数中将此变量设置为truefalse.

The best way to do this is to use a boolean variable to check if the character is touching the ground or not. You can set this variable to true or false in the OnCollisionEnter2D and OnCollisionExit2D functions.

创建一个名为"Ground"的标签.将所有地面Gameobjects更改为此标签,然后下面的示例应防止多次跳跃.

Create a tag called "Ground". Change all your ground Gameobjects to this tag then the example below should prevent multiple jumping.

bool isGrounded = true;

private float jumpForce = 2f;
private Rigidbody2D myRigidBody2D;

void Start()
{

    myRigidBody2D = GetComponent<Rigidbody2D>();

}

private void Update()
{
    if (Input.GetButtonDown("Jump") && isGrounded)
    {
        myRigidBody2D.AddForce(new Vector2(0, jumpForce));
    }
}

void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true;
    }
}

void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = false;
    }
}

这篇关于Unity2D防止角色多次跳跃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆