- Home /
Raycast and box collider not working properly
I'm having some weird problems with mouse events, mouse raycast and box collider. Sometimes raycast not hitting the box collider even tho my mouse is right above it. But if i move the mouse to the center of the box, the raycast hits.
This is weird bcuz i was expecting the ray to hit the box at any area of it. Can it be the fact that the z scale of box collider is very small ? Or it depends on the angle of camera ? I use Camera.main.ScreenPointToRay(Input.mousePosition) to get the ray for collision. And same happens of standard OnMouseEnter() it doesnt hit on certent areas of box, close to its margins.
green points raycast hit
red points miss
Anyone else had this problem or got any idea why this happens ?
Answer by Owen-Reynolds · Mar 15, 2014 at 02:29 PM
Don't think it's either of the things you mentioned (cam angle, box thickness.)
ScreenPointToRay completely accounts for camera angle and perspective. It uses the same math that placed the pixels in the first place.
Box thickness can matter in physics, where you might "step through" something thin, but ray casts use math. There's a formula for a line hitting a plane, and so on. But, if you're worried, make it thicker and try.
I'd say do more testing. Move the box and camera around more. Make sure to keep a rendered cube on it (maybe make it 50% transparent, if it blocks to much.) Maybe the box isn't where you think it was. Print what you're hitting. Maybe some other trigger is in the way of that edge. Check the near camera plane in Scene view (shouldn't matter, since the ray starts from there and drawing starts there, so if you can see it you can hit it. But if the box overlaps... .)
Answer by Goerky · Aug 10, 2021 at 09:38 AM
This Thread is by now over 6 years old, but in case someone stumbles upon this having the same problem (like me), here is the solution:
Layers
Even if you are doing a "2D game" it is still 3D for Unity. If multiple Colliders overlap on the same Depth/ Z-Axis, Unity cannot figure out which one to hit. I dont know why or how it "defaults" to accepting overlaying Colliders within the mentioned circle, but my guess would be their distance to the camera for some form of prioritization.
So the Answer is to give each overlapping Collider's GameObject its own Z-Axis-Value, even if you only work within the 2D-Game's X and Y Dimensions. For Sprites, this problem either not arizes or if it does, you can use the "Sorting Layers" of its GameObject's Sprite Renderer. Make sure to not confuse them with the "Layers" in the top right corner of the Editor - those are for Raycasting. The camera looks towards positive Z per default, meaning that you would increase the Collider's "Layers" (their Z-Axis-position) like 1, 2, 3, ... OR you take a value as upper limit, eg. 10, and work your way back (10 as background, 9 for obstacles, 8, 7, ..., 1)