检查对象是否与任何东西发生碰撞

时间:2017-07-06 10:34:35

标签: c# unity3d

有没有办法检测播放器(带有刚体)对象上的对撞机是否与2D环境中的任何其他对撞机碰撞?

3 个答案:

答案 0 :(得分:4)

不是本身,但有两种方法可以获取信息。保持int计数器最简单,并在OnCollisionEnter中递增,在OnCollisionExit递减。当计数器为0时,没有碰撞。

另一种方法是告诉你哪些碰撞器是重叠的,但如果它们正在接触则不一定是使用物理函数。注意你有哪种类型的对撞机 - 球体,胶囊,盒子。了解对撞机的大小/形状/位置后,您可以拨打Physics.OverlapBoxPhysics.OverlapCapsulePhysics.OverlapSphere。赋予函数与对撞机相同的形状,它将返回与该空间重叠的对撞机。 (对于2D对撞机,您可以使用Physics2D.Overlap*功能。)

答案 1 :(得分:1)

/ edit - 实际上piojo对计数器的想法更好,只需使用int而不是bool。 一种方法是在你的脚本中添加一个名为collisions的int并将其设置为0.然后,如果在任何时候,对撞机触发OnCollisionEnter,只需递增它,然后在OnCollisionExit中递减它。 这样的东西应该适用于3D:

public int collisions = 0;

void OnCollisionEnter(Collision collision)
{
    collisions++;
}

void OnCollisionExit(Collision collision)
{
    collisions--;
}

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html

https://docs.unity3d.com/ScriptReference/Collider.OnCollisionExit.html

答案 2 :(得分:0)

我不明白所有号码的保留情况。我刚刚做了这个,因为当我的角色跳跃或从边缘掉下来并且效果很好时。

我的球员和地形都有碰撞器。我用#34; Ground"标记了我的地形。标签。
然后用 OnCollisionStay()

检查我目前是否正在与对撞机接触
void OnCollisionStay(Collision collision)
{
    if (collision.collider.tag == "Ground")
    {
        if(animator.GetBool("falling") == true)
        {
            //If I am colliding with the Ground, and if falling is set to true
            //set falling to false.
            //In my Animator, I have a transition back to walking when falling = false.
            animator.SetBool("falling", false);
            falling = false;
        }
    }
}

void OnCollisionExit(Collision collision)
{
    if (collision.collider.tag == "Ground")
    {
        //If I exit the Ground Collider, set falling to True.
        //In my animator, I have a transition that changes the animation 
        //to Falling if falling is true.
        animator.SetBool("falling", true);
        falling = true;
    }
}

void OnCollisionEnter(Collision collision)
{
    if (collision.collider.tag == "Obstacle")
        {
             //If I collide with a wall, I want to fall backwards.
             //In my animator controller, if ranIntoWall = true it plays a fall-
             //backwards animation and has an exit time.
            animator.SetBool("ranIntoWall", true);
            falling = true;
            //All player movement is inside of an if(!falling){} block
        }
}
相关问题