[英]Detecting collision for 2 colliders using physics2d
我有一个物体与圆形对撞机2d,以及一个物体与盒子对撞机2d。 我如何检测圆形对撞机何时撞到盒子对撞机的顶部边缘。 假设没有物体旋转。 我想在代码C#中做到这一点
当某些东西与包含此脚本的对象发生冲突时, OnCollisionEnter会触发,如下所示:
void OnCollisionEnter(Collider collider)
{
foreach(CollisionPoint contact in collider.contacts)
{
//Do something
}
}
上面的内容为您提供了碰撞的接触点列表,通过它可以确定碰撞发生的位置。 如果您只需要在指定位置检测碰撞,则可以使用另一种方法,可以将不可见的子对象放置在多维数据集中,并在需要的位置放置一个对撞机。
编辑:
既然您提到了射线广播,我可以想到有两种方法可以实施这些方法。 首先是将其从立方体向上发射,但这存在仅从1点发射光线的问题,这意味着可能会丢失一些碰撞(取决于立方体和球体的大小)。
突然想到的第二种方法是将光线平行于立方体发射。 这听起来可能有点不合常规,而且我还没有测试过,但是从理论上讲应该可以。 将其粘贴在您的立方体中:
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.