So I have a problem I created an animation for my door and that went successfully and my script works just fine. But in my script it opens and closes the door all in one button push. How would I fix this?
Here’s my code:
#pragma strict
var theDoor : Transform;
private var drawGUI = false;
private var doorIsClosed = true;
function Update ()
{
if (drawGUI == true && Input.GetKeyDown(KeyCode.E))
{
changeDoorState();
}
}
function OnTriggerEnter (theCollider : Collider)
{
if (theCollider.tag == "Player")
{
drawGUI = true;
}
}
function OnTriggerExit(theCollider : Collider)
{
if (theCollider.tag == "Player")
{
drawGUI = false;
}
}
function OnGUI ()
{
if (drawGUI == true)
{
GUI.Box (Rect ( Screen.width*0.5-51, Screen.height*0.5, 102, 22), "E open");
}
}
function changeDoorState()
{
if (doorIsClosed == true)
{
theDoor.animation.CrossFade("Open");
doorIsClosed = false;
}
if (doorIsClosed == false)
{
theDoor.animation.CrossFade("Close");
doorIsClosed = true;
}
}
Perhaps you could make this SUPER easy and do something like
var animate : AnimationClip
function Update ()
if(Input.GetKeyDown(“e”)){
animation.clip = animate;
animation.Play();
}
Attach this too your door with the animation attached and you should be good tell me if not.
,Try using GetKeyUp.
I’m betting that since it’s in Update() that you are actually getting several calls to changeDoorState() during the fraction of time that the key is held down. Throw a debug in there and check it out.
I am using raycasting to do this. Here is my script that you can use.
#pragma strict
private var guiShow : boolean = false;
private 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") //make sure to tag your door "Door" without the exclamtion points in the transform.
{
guiShow = true;
if(Input.GetKeyDown("e") && isOpen == false) // use any key you want to i chose e
{
door.animation.Play("DoorOpen"); //this is the opening animation that i used
isOpen = true;
guiShow = false;
}
else if(Input.GetKeyDown("e") && isOpen == true)
{
door.animation.Play("DoorClose"); //this is the closing animation i used
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), "Press e"); //this part is not needed
}
}