Detecting whether hit point was left or right of the center of rotating box collider

I’m using Raycasting for collision detection in a 2d topdown game.

I know I can detect which side of my box collider has been hit by calculating the dot product of the axis and the hit normal. This will tell me if I’ve hit the front, side or back of the box.

I can also tell how offset the hit point was from the center by calculating the Vector3.Distance of the hit point and the box collider’s center.

But I also want to know whether the offset was to the right or to the left of the center. I can tell I hit the front of the box and that I was 0.5 from the center, but not whether that 0.5 was on the left side or right side of the center.

The enemies with the box colliders also rotate, so simply comparing the position.x with the hit point x value doesn’t help.

Below is an image to illustrate. I’m not interested in how deep the hit point is, so the Y component is irrelevant.

125551-example.jpg

I’m not 100% sure I follow what you’re trying to get at (maybe an example of what a left or right side hit is for in your game would help?), but here are some tools that might help get what you want:

You can get the Right vector of your object to establish the world space axis that defines the “local X”.

It sounds like you already have the collision location from the collision event. The worldspace collision location minus the world space center location gives you the offset vector between the center and the hit position.

If you project the offset vector (Unity - Scripting API: Vector3.Project) on your Right Vector you get a vector that points to the side of center that you were hit on.

Alternatively, you could put your worldspace offset vector in with your worldspace forward vector into Vector2.SignedAngle (Unity - Scripting API: Vector2.SignedAngle) and get a positive or negative number out. Whether it’s positive or negative tells you which side you got hit on.

Hope some of that gets you what you need!