Unity-检查播放器是否接地不工作 [英] Unity - Checking if the player is grounded not working

查看:121
本文介绍了Unity-检查播放器是否接地不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望播放器接地时播放器跳起来.

I want the player to jump when the player is grounded.

private void OnTriggerStay(Collider other)
{
    if(other.gameObject.layer == 8)
    {
        isGrounded = true;
    }else { isGrounded = false; }
}

生成时播放器处于播音状态.玩家跌落到带有标签Ground的地形后,isGrounded仍然为假.当我将isGrounded手动设置为true并再次跳转时,碰撞后仍然为true.我也不希望播放器在空中跳两次,我可能已经编码了,但是由于出了点问题而无法正常工作.

The player is on air when spawning. After the player falls to the Terrain, which has the tag Ground, isGrounded is still false. When I set isGrounded manually true and jump again, it's still true after collision. I also don't want the player to double jump in the air, which I probaly already coded but is not working because something is wrong.

OnTriggerStay更改为OnTriggerEnter不会更改任何内容.我希望你能帮助我.

Changing OnTriggerStay to OnTriggerEnter doesn't change something. I hope you can help me.

推荐答案

不要不要使用OnTriggerStay进行此操作.不能保证这是真的.

Do not use OnTriggerStay to do this. That's not guaranteed to be true very time.

在调用OnCollisionEnter时将isGrounded标志设置为true.调用OnCollisionExit时将其设置为false.

Set isGrounded flag to true when OnCollisionEnter is called. Set it to false when OnCollisionExit is called.

bool isGrounded = true;

private float jumpForce = 2f;
private Rigidbody pRigidBody;

void Start()
{
    pRigidBody = GetComponent<Rigidbody>();
}

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

void OnCollisionEnter(Collision collision)
{
    Debug.Log("Entered");
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = true;
    }
}

void OnCollisionExit(Collision collision)
{
    Debug.Log("Exited");
    if (collision.gameObject.CompareTag("Ground"))
    {
        isGrounded = false;
    }
}

在您说它不起作用之前,请检查以下内容:

Before you say it doesn't work, please check the following:

  • 您必须将RigidbodyRigidbody2D连接到播放器.

如果是Rigidbody2D,则必须使用OnCollisionEnter2DOnCollisionExit2D.

If this Rigidbody2D, you must use OnCollisionEnter2D and OnCollisionExit2D.

您必须使用IsTrigger将对撞机连接到播放器 禁用.

You must have Collider attached to the player with IsTrigger disabled.

确保您没有通过以下方式移动Rigidbodytransform.positiontransform.Translate.你必须搬家 Rigidbody MovePosition 函数.

Make sure you are not moving the Rigidbody with the transform such as transform.position and transform.Translate. You must move Rigidbody with the MovePosition function.

这篇关于Unity-检查播放器是否接地不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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