I have a 2d game where a ship collides with meteorites.
Based on how hard was the impact I will then detract ship health.
To me this sounds like a very simple thing but I was unable to find this collision info for Collider2D.
What am I doing wrong?
I have a 2d game where a ship collides with meteorites.
Based on how hard was the impact I will then detract ship health.
To me this sounds like a very simple thing but I was unable to find this collision info for Collider2D.
What am I doing wrong?
well, you know what hit you should be able to get its velocity
You’ll need to be specific, there’s no such thing as “how hard” in physics. All I can point out is what’s already there but you said you were unable to find it so I’m not sure how else to help.
As you’ve already seen:
but there’s a huge difference between a feather hitting you at 1 m/s and a car so you can scale this by mass.
… and per contact you get:
The normal impulse is what was required to keep them separated and could work well for you.
Thank you! That was exactly what I was looking for.
For posterity here is the code I ended up with:
private void OnCollisionEnter2D(Collision2D collision)
{
var impactForce = collision.contacts.Sum(x => x.normalImpulse + x.tangentImpulse);
var damage = Mathf.Max(0, impactForce - _collisionResistance);
Debug.Log($"Damage taken: {damage}");
}
I’d avoid using Linq but that’s your choice. Also, using the “contacts” field also produces garbage as it has to create a list.
You can use the non-allocating stuff for performance:
Reuse a List in your script. It’ll automatically have the correct capacity but after a few calls you won’t have any allocation etc.