How To Decide To Damage Between Colliding Cars

Hi everyone. I try to make 2d bumper cars game. And i have a challanging question for you. Each car has 2d capsule collider and a rigidbody. I use rigidbody to move cars. And when i hit a car, both cars emit oncollissionenter event. I just want to decrease health value of the car which is hit by other. But how can i decide that which one hit the other one? For example:

private void OnCollisionEnter2D(Collision2D collision) {
    BumperCar bumpercar = collision.collider.GetComponent<BumperCar>();
    bumpercar.TakeDamage(10); 
}

If i do something like that, both cars take damage. But i just want only one car which is hit by other to take damage. How can i do that? Do you have any idea?

You could attach several different colliders to the car.

E.g. one for each corner of the car - invulnerable and a little exposed, a car hit there takes little or no damage - and one for each edge i.e. front, back, left, right which are more vulnerable and a car hit there take more severe damage.

So the driving get’s a little bit tactical and you need some skill: how to bump with my corner into the other car - without exposing my weeknesses to.

Maybe you could offer different cars with different strong and weak zones for different driving/bumping tactics.

Wanna see the game then :smiley:

Here is a simple solution:

Check the directions of the colliders, if they cross the other collider, they are bumping it. If they both cross each other (front collision), both should lose health.

Since you are working on objects with similar masses, it should be ok.


If you need a more complex solution which imply mass and velocity of the colliders, look at momentum collision solvers.

Here are useful information on momentums: https://www.physicsclassroom.com/calcpad/momentum

Like said above, assuming that you hit enemy cars with the front of your car, you can check for collision between a collider at the front your car with any part of the enemy. Then take health from the enemy.

Hi guys. I was about to give up but i think i have found my solution:

private void OnCollisionEnter2D(Collision2D collision)
{
	if (collision.gameObject.CompareTag("Player"))
	{
		ContactPoint2D contactPoint = collision.GetContact(0);
		float rigidBodyPointVelocityMagnitude = collision.rigidbody.GetPointVelocity(contactPoint.point).magnitude;
		float otherRigidBodyPointVelocityMagnitude = collision.otherRigidbody.GetPointVelocity(contactPoint.point).magnitude;

		if (rigidBodyPointVelocityMagnitude < otherRigidBodyPointVelocityMagnitude)
		{
			TakeDamage(otherRigidBodyPointVelocityMagnitude * damageAmount);
		}
	}
}

Basicly i have found a way to get velocity at hit(contact) point. I assume that car is hit by other if it has lower velocity. This solution seems like working for me :slight_smile: