I’m trying to do a simple BoxCast for ground detection but for some reason it’s returning null 99.9% of the time, if I jitter around enough I can sometimes get it to detect the ground but it’s extremely random.
Physics.BoxCast(transform.position, transform.lossyScale / 2, Vector3.down, out RaycastHit hitInfo, transform.rotation, 0.1f);
This is the scene from my game, the star is the player character, I drew in the red box to show where I intended the boxcast to start and the green box is where it’s supposed to project to, roughly. Once the character falls and hits the floor due to gravity it should pick something up, but doesn’t.
Some things to note:
-I’m using the 3D physics just because it’s a 3D scene but I’m doing a 2D sidescrolling minigame within it
-I got a normal Raycast to work perfectly fine
-The player character has a Character Controller component
-The transform.lossyScale / 2 argument is just one of many things I’ve unsuccessfully tried that should resolve to 8, as the sprite is 16 units wide.
If anyone could help shed some light on this I’d be extremely grateful
I note you’re not specifying a LayerMask here so you’ll collide with everything, including any 3D Collider on the player character itself.
This is the Transform scale, not the size of the renderer (sprite or otherwise) so it’s not an absolute size. Only if the renderer is a unit square (when scale is 1,1,1) will this be the same as an absolute size.
The Renderer has Renderer.bounds but nothing will magically ensure it’s correct so you need to check what the size is by simply debugging it (Debug.Log to the console) to verify your assumptions. Or just draw the renderer bounds as a box to check it too so see if it’s useful. Don’t fall into the trap of assuming what you draw is what you’re querying.
Thanks for your help, I ultimately decided a SphereCast was better considering the spherical shape of the character controller hitbox, but you were right to suggest I use Debug.Log to verify what I was putting in. It turns out the number I needed wasn’t 8, but about 3.849002. I mistakenly thought all the info I would’ve needed would be right there in the inspector. I have the precise ground detection I need now so thanks so much for pointing me in the right direction!
Well if you ever decide to come over to the Dark Side and use 2D physics then I can give you more info being as that’s my area. There’s also much better features for ground detection etc.