Unity - 检查播放器是否接地不起作用 [英] Unity - Checking if the player is grounded not working
问题描述
我希望玩家在接地时跳跃.
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
标签的 Terrain 后,isGrounded
仍然是 false.当我手动将 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:
您必须将
Rigidbody
或Rigidbody2D
附加到播放器.
You must have
Rigidbody
orRigidbody2D
attached to the player.
如果这个 Rigidbody2D
,你必须使用 OnCollisionEnter2D
和OnCollisionExit2D
.
If this Rigidbody2D
, you must use OnCollisionEnter2D
and
OnCollisionExit2D
.
您必须使用 IsTrigger 将 Collider 附加到播放器已禁用.
You must have Collider attached to the player with IsTrigger disabled.
确保您没有通过变换移动 Rigidbody
,例如作为 transform.position
和 transform.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屋!