简体   繁体   English

使用Physical2D检测2个对撞机的碰撞

[英]Detecting collision for 2 colliders using physics2d

I have an object with circle collider 2d, and an object with box collider 2d. 我有一个物体与圆形对撞机2d,以及一个物体与盒子对撞机2d。 how do i detect when the circlecollider hits the top edge of the box collider. 我如何检测圆形对撞机何时撞到盒子对撞机的顶部边缘。 assuming none objects have any rotation. 假设没有物体旋转。 i want to do this in code C# 我想在代码C#中做到这一点

OnCollisionEnter triggers when something collides with the object containing this script, used like this: 当某些东西与包含此脚本的对象发生冲突时, OnCollisionEnter会触发,如下所示:

void OnCollisionEnter(Collider collider)
{
    foreach(CollisionPoint contact in collider.contacts)
    {
        //Do something
    }
}

The above will give you a list of contact points for the collision, via which you should be able to determine where the collision occurred. 上面的内容为您提供了碰撞的接触点列表,通过它可以确定碰撞发生的位置。 An alternative method if you only need to detect collisions at a specified location, you could place an invisible child object within your cube, with a collider at the spot you want. 如果您只需要在指定位置检测碰撞,则可以使用另一种方法,可以将不可见的子对象放置在多维数据集中,并在需要的位置放置一个对撞机。

Edit: 编辑:

Since you mentioned raycasts, there's 2 ways I can think of that these could be implemented. 既然您提到了射线广播,我可以想到有两种方法可以实施这些方法。 The first is to fire it upwards from the cube, but this has the issue of the ray firing from just 1 point, meaning some collisions might be missed (depending on the size of the cube & sphere). 首先是将其从立方体向上发射,但这存在仅从1点发射光线的问题,这意味着可能会丢失一些碰撞(取决于立方体和球体的大小)。

The second method that pops to mind is to fire the ray parallel to the cube. 突然想到的第二种方法是将光线平行于立方体发射。 This might sound a bit unorthodox, and I haven't tested it, but in theory it should work. 这听起来可能有点不合常规,而且我还没有测试过,但是从理论上讲应该可以。 Stick it in your cube: 将其粘贴在您的立方体中:

void Update
{
    Vector3 start = this.transform.position;
    Vector3 end= this.transform.position;

    //This attempts to place the start & end point just above the cube
    //This of course assumes the cube isn't rolling around. If that's the case
    //then these calculations get quite a bit more complicated
    //Additionally the 0.01 might need adjusting if it's too high up off the cube
    start.y += this.renderer.bounds.y/2 + 0.01f;
    end.y += this.renderer.bounds.y/2 + 0.01f;

    start.x -= this.renderer.bounds.x/2;
    end.x += this.renderer.bounds.x/2;

    Ray ray = new Ray(start, end);
    RaycastHit hit;

    if(Physics.Raycast(ray, out hit, start.x-end.x) && hit.name == "mySphere")
    {
        //Theoretically, the sphere hit the top of the box!
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM