How do you do a raycast in empty space?

I’m using Raycasting to point my gun where my cursor is in the 3D world. I can point at the terrain, crates, enemies but Raycasting doesn’t work on the empty space. How would I be able to Raycast in the spaces that aren’t colliders? Do I use some sort of skybox?

If the ray you’re casting hits nothing, use some distance from the camera as the aim point -

eg

var aimDistance : float = 10.0;
var rch : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay( Input.mousePosition );

if ( Physics.Raycast( ray, rch, aimDistance ) ) {
  aimpoint = rch.point;
} else {
  aimpoint = ray.origin + ray.direction * aimDistance;
}
1 Like

This is works well for me… thanks…

Try this:

RaycastHit hit;

if(hit.collider == null)
return;

Check if the RaycastHit’s collider is null.

You’re replying to a post from 2011. Please don’t necro threads.