- Home /
Using raycast to determine the thickness of a collider
I'm trying to make a script that gives a bullet realistic penetration effects on impact with objects. To do this, I need to know the (effective) thickness of the object (collider, to be precise) the bullet collides with. To do this, I made two raycast operations in opposite directions along the bullet's velocity with a separation of two meters. Here's the code:
//rb is the rigidbody of the bullet
Ray ray = new Ray(transform.position, rb.velocity);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, rb.velocity.magnitude ))
{
RaycastHit[] otherDirectionHits;
otherDirectionHits = Physics.RaycastAll(hit.point + ray.direction * 2, -ray.direction, 2);
float effctiveThickness = 0;
for (int i = otherDirectionHits.Length - 1; i > 0; i--)
{
if (hit.rigidbody == otherDirectionHits[i].rigidbody)
{
effctiveThickness = 2 - otherDirectionHits[i].distance;
break;
}
}
Debug.Log(effectiveThickness)
}
However, whenever the bullet hits anything, the Debug.Log outputs 0.
I have tested this script with different sizes of box colliders, static mesh colliders, terrain colliders and convex mesh colliders and the output is always the same.
What have I done wrong? Is it with the raycast API? I would appreciate any kind of help. Thanks.
Answer by _dns_ · Nov 05, 2018 at 03:12 PM
Hi, I would use Debug.DrawLine or .DrawRay to see what is happening. Also, the for() on line 9 should include the case where i == 0 (using "i >= 0"). I would also try to use some non-allocating versions of Physics methods, it's always a good optimization to do, once it works of course :-)
Thank you. I have tested it again with the i > 0 changed to i > = 0 and it worked. I'm new to C# so I'm not sure if the for loop is pre-condition or post-condition or when the increment is executed. Guess I'll have to be more careful next time to avoid these careless mistakes.