- Home /
How do I get my door to work?
Basically I've made a sliding door that opens when the player is near but I want to add another condition so that the player has to press "e" to open it aswell as being nearby. Here is my code.
using UnityEngine;
using System.Collections;
public class Doors : MonoBehaviour {
Animator animator;
bool doorOpen;
void Start()
{
doorOpen = false;
animator = GetComponent<Animator>();
}
void Update () {
if (Input.GetKeyDown ("e"))
print ("e key was pressed");
}
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player" && Input.GetKeyDown("e"))
{
Debug.Log ("e was pressed");
doorOpen = true;
DoorControl ("Open");
}
}
void OnTriggerExit(Collider col)
{
if(doorOpen)
{
doorOpen = false;
DoorControl ("Close");
}
}
void DoorControl(string direction)
{
animator.SetTrigger(direction);
}
}
I know Input.GetKeyDown only works in update but I'm unsure how I can make the OnTriggerEnter combine with it. Anyone know how?
Thanks.
Answer by flaviusxvii · Sep 07, 2014 at 01:15 PM
OnTriggerEnter http://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html only fires once! At the moment of collision! (And again if the player leaves and comes back). So the way you have this written it would only work if the player was holding down 'e' when they hit the collider. You want to track these two events independently. if(playerIsCloseEnough && playerHasPressedE) { openDoor(); }
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is it possible to change keyboard input inGame 1 Answer
How to push down a button and hold it through script? 0 Answers
Keycode else 1 Answer