- Home /
input button while in a trigger?
i am working on a fps game, and was making a switch to open some doors, i attached two colliders to the switch, one trigger which extends ahead of the trigger, to know whether the player is there or not, and other collider so that the player does not pass through it, it is placed on a wall, i can get the door to open when i enter the trigger, but the problem arises when i try to implement the door opening when the button e, is being pressed while the player is in the trigger, here is the script
public class Switch : MonoBehaviour { public GameObject door; public GameObject player;
void OnTriggerEnter(Collider col)
{
if(col.gameObject.name=="Player")
{
if(Input.GetButtonDown("Use"))
{
Debug.Log ("door open");
door.transform.Translate (0, 5, 0);
}
}
}
}
here's the script attached to the switch.
Answer by 5c4r3cr0w · Jun 10, 2016 at 12:46 PM
You need to use OnTriggerStay() function instead of OnTriggerEnter().
thanks man! it worked, but can you please explain why? was it because ontriggerenter returns just when the target is entering?
Yes. For more information check out this tutorial.
https://unity3d.com/learn/tutorials/topics/physics/colliders-triggers
Answer by xXx12aithexXx · Jun 10, 2016 at 04:33 PM
I think a good alternative is to have the door have it's collider and its trigger..... like I think you're saying
but I would disreguard the ontrigger function...
instead I would make a "action raycast"
using UnityEngine;
using System.Collections;
public class OpenDoorTest : MonoBehaviour {
public float actionDistance = 100;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
RaycastHit rayhit;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position,fwd,out rayhit,actionDistance)
{
if (rayhit.collider.CompareTag("DoorTrigger")
{
if (Input.GetKeyDown("E"))
{
//Create a door script with function
bool openclose = false
openclose = !openclose;
rayhit.collider.gameObject.GetComponent<DoorFunctionScript> ().opendoor = openclose;
}
}
}
}
}
sorry for the bad code snippet.
so, you are saying to forget about the switch, yeah, that could work too, but i am not any good with raycasts, can you please explain a bit