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
的地形后,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:
-
您必须将
Rigidbody
或Rigidbody2D
连接到播放器.
如果是Rigidbody2D
,则必须使用OnCollisionEnter2D
并
OnCollisionExit2D
.
If this Rigidbody2D
, you must use OnCollisionEnter2D
and
OnCollisionExit2D
.
您必须使用IsTrigger将对撞机连接到播放器 禁用.
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屋!