- Home /
Opening door.
Hello, I have this simple script of opening doors:
#pragma strict
private var guiShow : boolean = false;
var isOpen : boolean = false;
var door : GameObject;
var rayLength = 10;
function Update()
{
var hit : RaycastHit;
var fwd = transform.TransformDirection(Vector3.forward);
if(Physics.Raycast(transform.position, fwd, hit, rayLength))
{
if(hit.collider.gameObject.tag == "Door")
{
guiShow = true;
if(Input.GetKeyDown("e") && isOpen == false)
{
door.animation.Play("dooropen");
isOpen = true;
guiShow = false;
}
else if(Input.GetKeyDown("e") && isOpen == true)
{
door.animation.Play("DoorClose");
isOpen = false;
guiShow = false;
}
}
}
else
{
guiShow = false;
}
}
function OnGUI()
{
if(guiShow == true && isOpen == false)
{
GUI.Box(Rect(Screen.width / 2, Screen.height / 2, 100, 25), "Use Door");
}
}
Now.. I've put it in my character and it works etc. But I have to manually everytime change that variable door : GameObject to which door I want to open.
Could someone point me to the right way how to get this script to look itself/automatically for which door I'm looking at as now it only works for that one door as it needs to be manually changed from editor if you wanna open up another doors than that one.
Answer by MSpiteri · Jul 11, 2014 at 10:42 AM
Hello there,
You do not need the door variable at all.
In the Raycasting command, remember that the variable 'hit' will contain the information about the object that you have hit with the raycast. So, hit.collider.gameObject will refer to the door.
Basically, you should replace this:
door.animation.Play("dooropen");
with this
hit.collider.gameObject.animation.Play("dooropen");
And do the same for the close door.
This causes every door open up on wrong side, but it's fixable by doing animations again.. Thanks god I didnt do alot of those door open/close animations. Thank you anyways it works and it's easy to fix at this point still.
For opening and closing a door, I suggest that you make the door open vertically (ie. it moves upwards) like in Doom 1 and Doom 2 :) That will always open properly ;)
Answer by PiraLezz · Jul 11, 2014 at 11:38 AM
//function in the doors script
var open : boolean = false;
function OpenClose()
{
if(open)
{
animation.Play("dooropen");
open = true;
}
else
{
animation.Play("DoorClose");
open = false;
}
}
// when you must open/close a door you call the OpenClose function of the door
if(Physics.Raycast(transform.position, fwd, hit, rayLength))
{
if(hit.collider.gameObject.tag == "Door")
{
guiShow = true;
if(Input.GetKeyDown("e") && isOpen == false)
{
hit.transform.SendMessage("OpenClose",SendMessageOptions.DontRequireReceiver);
guiShow = false;
}
}
else
{
guiShow = false;
}
}