[英]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.