- Home /
Using a gameObject as Raycast origin position?
Hello again Unity Answers.
I've got a script that that spawns bad guys if the path of the Ray cast is clear. Here's a snippet...
public float rayLength;
void rayCastOne()
{
RaycastHit hit; //Var for if the Ray Cast has hit something or not.
Debug.DrawRay(transform.position, -transform.forward * rayLength);
if (Physics.Raycast(transform.position, -transform.forward, out hit, rayLength))
I understand you can set the length of the Ray with the 4th argument with a variable but is it possible to set the origin (currently set as transform.position) as a game object?
So for example -
public float rayLength;
public GameObject spawnPointM;
void rayCastOne()
{
RaycastHit hit; //Var for if the Ray Cast has hit something or not.
Debug.DrawRay(spawnPointM, -transform.forward * rayLength);
if (Physics.Raycast(spawnPointM, -transform.forward, out hit, rayLength))
So then it'll look at the position of spawnPointM and procedure a Ray Cast from it where ever I put spawnPointM.
Or does it need to be more complicated? (Like having to save the X, Y and Z coordinates of spawnPointM as variables then spitting them out into the RayCast as a vector3?)
Thanks ahead!
Answer by Joyrider · Aug 19, 2013 at 03:25 PM
Just reference your GameObject and access its transform, instead of the transform of the object the script is on.
if (Physics.Raycast(spawnPointM.transform.position, -spawnPointM.transform.forward, out hit, rayLength))
Answer by DaveA · Aug 19, 2013 at 03:25 PM
Not complicated, that should work (not having taken a long look at your code though)
Your answer
Follow this Question
Related Questions
Raycast hit not detected on cube 1 Answer
Raycast detects box collider, but not capsule collider 0 Answers
How do I rotate an object based on the terrain? 1 Answer
RaycastHit direction and start position 0 Answers
Boxcast vs Raycast Oddities 1 Answer