- Home /
Possibly simple Raycasting question
Hey guys, so I have a raycast script attached to my FPS controller, with the raycast coming out of my main camera/fps camera.
What the script is meant to do is when the player approaches the tagged door within the range, then lets you have the option to press space to go to the next area. This all works fine. However when I go toward the door, looking at a weird angle (but still with the ray on the door) it doesn't detect it, or it still thinks it is being detected even when the player is outside the range. Here's the script if anyone could help :)
var Hit: RaycastHit;
var Range : float;
var mesh :GameObject;
var DoorActive: boolean = false;
private var count: int = 0;
var myStyle1 : GUIStyle;
var Level : String;
function OnGUI () {
if(DoorActive == true){
GUI.color = new Color( 1,1,1, 0.5f);
GUI.Label (Rect (Screen.width/2-50, Screen.height/2-25, 100, 50), "Space to Enter", myStyle1);
}else{
GUI.Label (Rect (Screen.width/2-50, Screen.height/2-25, 100, 50), "o", myStyle1);
}
}
function Update(){
if(DoorActive == true){
if(Input.GetKey(KeyCode.Space)){
count = count + 1;
Debug.Log("Door presses" + count);
Application.LoadLevel (Level);
DoorActive = false;
//what happens when press
}
}
var DirectionOfLine : Vector3 = mesh.transform.TransformDirection(Vector3.forward);
Debug.DrawRay(mesh.transform.position, DirectionOfLine * Range, Color.yellow);
if(Physics.Raycast(mesh.transform.position, DirectionOfLine, Hit, Range)){
if(Hit.collider.gameObject.tag == "Door"){
// Debug.Log("You have hit the door, press space to open");
DoorActive = true;
}
}else{
DoorActive = false;
}
}
Answer by Tourist · Dec 13, 2012 at 10:15 AM
I think you forgot an else block. If the raycast hits something that is not tagged "Door", the flag DoorActive is not set to false.
If a first raycast hits the door then when you re moving around the raycast hits something else, the flag is true and you can be miles away from the door.
That did it! Thanks! I originally put an else block there, but then replaced it with the parent else block. It does make sense to have both. Thanks a lot!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Joystick Raycast Problem? 2 Answers
Straight Raycast Shooting 1 Answer