- Home /
Raycast Never Hits Anything?!
I have a script to close doors automatically in my game, however I don't want them to close if the player is in the doorway. I'm trying to use a raycast/spherecast to see if the player is nearby, but the raycast never hits anything. I've been trying different methods for hours, I never get a different result... Any help would be greatly appreciated. Here's the code I have so far. The variables in the pysics.raycast are just the ones i tried last, i've tried countless other combinations.
if (doorIsOpen)
{
doorTimer += Time.deltaTime;
if (doorTimer > 3.5)
{
bool isPlayer = false;
RaycastHit charCheck;
//if (Physics.SphereCast(currentDoor.transform.position, 1.2f, new Vector3(1f,0.5f,1f), out charCheck, 1.2f))
Vector3 fwd = currentDoor.transform.TransformDirection(-Vector3.up);
if (Physics.Raycast(currentDoor.transform.position, fwd, out charCheck, 2f))
{
print(charCheck.collider.gameObject.tag);
if (charCheck.collider.gameObject.tag == "Player")
isPlayer = true;
else
isPlayer = false;
}
if (!isPlayer)
{
// Call the door function with parameters to close the door
Door(CloseSound, false, "close", currentDoor);
// reset the timer
doorTimer = 0.0f;
}
}
}
Answer by Posly · Feb 20, 2012 at 10:42 PM
Why don't you just use "Vector3.Distance"? It checks how far away two objects are from each other.http://unity3d.com/support/documentation/ScriptReference/Vector3.Distance.html
I haven't used Vector3.Distance, not sure how it works. I'll look at the documentation and give it a try.
Answer by sankou134 · Feb 20, 2012 at 10:54 PM
Thanks a ton for the solution! Vector3.Distance was way better than what I was trying. Here's the working function:
if (doorIsOpen)
{
doorTimer += Time.deltaTime;
if (doorTimer > 3.0)
{
float charDist = Vector3.Distance(currentDoor.transform.position, transform.position);
print(charDist);
if (charDist > 3)
{
// Call the door function again with parameters to close the door
Door(CloseSound, false, "close", currentDoor);
// reset the timer
doorTimer = 0.0f;
}
}
}