How to detect on which side of the rectangle collision happened

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ariton


Im making a simple top down game about tanks shooting each other in a little arena. I want it so hits to the side and back of the tank deal more damage then direct hits to the front of the tank. I currently have Area2D with Rectangle shape to detect when the missile hits the tank, but I dont know how I could detect on which side of the rectangle the collision occured.

Right now im thinking of simply adding 4 Area2D nodes on each side of the tank and if missile hits the Area2D placed in the front, it means it hit the front of the tank, if it hits Area2D placed on left/Right it hit the sides, but I see some issues with this approach, for example what if the missile hits the tank in the corner where the Area2Ds are intersecting and the collision is detected in both Front Area and the sides then where did the collision occur?? Front or the side??

Does anyone know any better approach on how I could detect which side of the tank the missile hit?

You could check that angle that the collision occurred at relative to the centre of the rectangle, and compare that with the rotation of the rectangle.

SteveSmith | 2023-01-15 11:45

:bust_in_silhouette: Reply From: LeslieS

You can check body.position in comparison to the tank.position
For example:

if body.global_position.x < global_position.x:
    #body collided on the left side.

Code and answer from here.