Search Unity

Raycasting question

Discussion in 'Physics' started by TheSnowyDev, Aug 1, 2020.

  1. TheSnowyDev

    TheSnowyDev

    Joined:
    Feb 17, 2020
    Posts:
    51
    Hi! I was wondering if it is possible to instantiate an object at the end of a raycast if it doesn't hit something (or if it isn't easily possible, instantiate where the end of the ray would be). Any help would be appreciated.

    P.S. I checked the manual and API for raycasting, I can't really figure it out :/
     
  2. tjmaul

    tjmaul

    Joined:
    Aug 29, 2018
    Posts:
    467
    Yes, it is. I mostly copied the sample from Physics.Raycast:

    Code (CSharp):
    1. Vector3 fromPosition; // set this to wherever you want to cast from
    2. Vector3 direction; // set this to your direction
    3. float distance = 15f;
    4. if (Physics.Raycast(fromPosition, direction, out hit, distance, layerMask))
    5.         {
    6.             Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
    7.             Debug.Log("Did Hit");
    8.         }
    9.         else
    10.         {
    11.             Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
    12.             Debug.Log("Did not Hit");
    13.             Instantiate(somePrefab, fromPosition + distance * direction.normalized, Quaternion.identity);
    14.         }
     
    TheSnowyDev likes this.
  3. TheSnowyDev

    TheSnowyDev

    Joined:
    Feb 17, 2020
    Posts:
    51
    Okay, thanks a lot, man. I'm running a bit late on my project and you just made the game a whole bunch more playable
     
  4. TheSnowyDev

    TheSnowyDev

    Joined:
    Feb 17, 2020
    Posts:
    51
    Error being thrown: "The name 'direction' does not exist in the current context"

    Do I need to be using any additional namespaces, or is VS just being VS?
     
  5. tjmaul

    tjmaul

    Joined:
    Aug 29, 2018
    Posts:
    467
    Please don't just copy and paste.

    In line 2, direction is declared.. I don't know the position and direction in which you want to cast, so that's up to you. The takeaway for the question of how to spawn an object "at the end of a raycast" is another question: Where is the end of a raycast? In case of distance == Math.Infinity, there is none. In case of a finite distance, you can calculate it like this:

    Code (CSharp):
    1. Vector3 endOfRaycast = position + direction.normalized * distance
     
  6. TheSnowyDev

    TheSnowyDev

    Joined:
    Feb 17, 2020
    Posts:
    51
    RIGHT I FORGOT THAT DIRECTION WAS A VARIABLE. Derp.
     
  7. Meyhem6910

    Meyhem6910

    Joined:
    May 22, 2021
    Posts:
    1
    thank you so much im in a game jam and have less than a day left