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
Yes, it is. I mostly copied the sample from Physics.Raycast:
Vector3 fromPosition; // set this to wherever you want to cast from
Vector3 direction; // set this to your direction
float distance = 15f;
if (Physics.Raycast(fromPosition, direction, out hit, distance, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("Did not Hit");
Instantiate(somePrefab, fromPosition + distance * direction.normalized, Quaternion.identity);
}
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:
Vector3 endOfRaycast = position + direction.normalized * distance