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.
Answer by v-ercart · Oct 03, 2018 at 07:02 PM
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 (https://docs.unity3d.com/ScriptReference/Vector3.Project.html) 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 (https://docs.unity3d.com/ScriptReference/Vector2.SignedAngle.html) 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!
Perfect! Thanks for your answer. Using Vector3.Project gave me all the data I need.
Your answer
Follow this Question
Related Questions
Rotated object raycasting in wrong directions!!? 3 Answers
Merge two gameobjects and create a new one unity2D! 0 Answers
Why is a raycast not setting a maxDistance 0 Answers
how to prevent a kinematic rigidbody from going through static colliders 0 Answers
How do I make the player walk up walls using raycast? (making a mountain goat game prototype) 2 Answers