Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How do you do a raycast in empty space?

Discussion in 'Scripting' started by GibTreaty, Jan 15, 2011.

Thread Status:
Not open for further replies.
  1. GibTreaty

    GibTreaty

    Joined:
    Aug 25, 2010
    Posts:
    792
    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?
     
  2. Vicenti

    Vicenti

    Joined:
    Feb 10, 2010
    Posts:
    664
    If the ray you're casting hits nothing, use some distance from the camera as the aim point -

    eg

    Code (csharp):
    1. var aimDistance : float = 10.0;
    2. var rch : RaycastHit;
    3. var ray : Ray = Camera.main.ScreenPointToRay( Input.mousePosition );
    4.  
    5. if ( Physics.Raycast( ray, rch, aimDistance ) ) {
    6.   aimpoint = rch.point;
    7. } else {
    8.   aimpoint = ray.origin + ray.direction * aimDistance;
    9. }
     
    Lex4art likes this.
  3. ndrm

    ndrm

    Joined:
    Jul 25, 2020
    Posts:
    8
    This is works well for me.. thanks..
     
  4. teamtron3

    teamtron3

    Joined:
    Dec 16, 2022
    Posts:
    3
    Try this:

    RaycastHit hit;

    if(hit.collider == null)
    return;

    Check if the RaycastHit's collider is null.
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,623
    You're replying to a post from 2011. Please don't necro threads.
     
Thread Status:
Not open for further replies.