首页 > 解决方案 > C#SphereCast如何使用hitInfo

问题描述

我正在尝试制作一个我的角色可以跳跃的fps游戏。我正在使用 spherecast 来了解我的角色是否接地。这是我目前拥有的。

    public CapsuleCollider capsuleCollider;
void Update()
{
    if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = Vector3.up * jumpVelocity;
    }
}
private bool IsGrounded()
{
    float downCheck = capsuleCollider.bounds.extents.y + 0.1f;
    return Physics.SphereCast(capsuleCollider.bounds.center, capsuleCollider.bounds.size.x, Vector3.down, hit, capsuleCollider.bounds.extents.y + extraHeight);
}

不知道我与命中有什么关系。有人可以帮我吗?

标签: c#unity3d

解决方案


不知道我和 hit 有什么关系

无论你想要什么 ;)

Physics.SphereCasthit一个out参数,这意味着它的值将在Physics.SphereCast方法中分配。

你现在可以做同样的事情,例如

private bool IsGrounded(out RayCastHit hit)
{
    var downCheck = capsuleCollider.bounds.extents.y + 0.1f;
    return Physics.SphereCast(capsuleCollider.bounds.center, capsuleCollider.bounds.size.x, Vector3.down, out hit, capsuleCollider.bounds.extents.y + extraHeight);
}

或者您似乎无论如何都不需要它,因此您可以传入out var hit并进一步忽略它,或者-c#中实际上存在一些用于忽略out称为Discardsout _的参数的东西-您可以简单地传入

private bool IsGrounded()
{
    float downCheck = capsuleCollider.bounds.extents.y + 0.1f;
    return Physics.SphereCast(capsuleCollider.bounds.center, capsuleCollider.bounds.size.x, Vector3.down, out _, capsuleCollider.bounds.extents.y + extraHeight);
}

这告诉编译器您不使用该值,因此您甚至不必关心它的类型或名称。


就像旁注一样:您确定要执行SphereCast吗?这意味着你射出一个球体,看看它会在某个方向击中什么......你是否更愿意使用例如Physics.OverlapSphere


推荐阅读