Search Unity

  1. Unity 2020.1 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Raycasting question

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

  1. CloakedDaggerr

    CloakedDaggerr

    Joined:
    Feb 17, 2020
    Posts:
    30
    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:
    184
    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.         }
     
    CloakedDaggerr likes this.
  3. CloakedDaggerr

    CloakedDaggerr

    Joined:
    Feb 17, 2020
    Posts:
    30
    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. CloakedDaggerr

    CloakedDaggerr

    Joined:
    Feb 17, 2020
    Posts:
    30
    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:
    184
    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. CloakedDaggerr

    CloakedDaggerr

    Joined:
    Feb 17, 2020
    Posts:
    30
    RIGHT I FORGOT THAT DIRECTION WAS A VARIABLE. Derp.
     
unityunity