- Home /
commands.close.hint.6
check if player is colliding with a trigger
i need to check if The player is colliding with a trigger tagged "Dock" when they press "Q" and if its true then run "Water();" collision was never my forte so at the moment im pretty lost, especially since its been so long since ive done this. here's what i have so far:
public class VehicleAccess : MonoBehaviour {
public bool AccessBoat = true;
public bool AccessCar = true;
public bool AccessAirship = true;
public GameObject Player;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//If Q is pressed
if(Input.GetKeyDown (KeyCode.Q))
{
//check for player's collision with game object tagged Dock
//if true
Water();
}
}
//If player is trying to enter the Ship
void Water()
{
Debug.Log("Water");
}
}
I know its not much but as i said i was never good at collision, which is all i need to understand and implement the collision detection to move on.
Answer by Tomer-Barkan · Oct 11, 2013 at 07:20 PM
Add a boolean variable, set it to true when the collision starts, and false when the collision ends.
When the player presses Q, check that boolean.
public class VehicleAccess : MonoBehaviour {
private bool touchingDock = false;
public GameObject Player;
// Update is called once per frame
void Update () {
//If Q is pressed
if(Input.GetKeyDown (KeyCode.Q))
{
//check for player's collision with game object tagged Dock
if (touchingDock)
Water();
}
}
void OnTriggerEnter(Collider other) {
if (other.tag == "Dock") {
touchingDock = true;
}
}
void OnTriggerExit(Collider other) {
if (other.tag == "Dock") {
touchingDock = false;
}
}
}
okay so i understand a little now, but something i noticed... do the OnTriggerEnter and OnTriggerExit of the collider only happen once?
Yes, once per collision. The first frame after they collide, OnTriggerEnter()
is called. Then as long as they are still in collision (ie still occupy the same space), the OnTriggerStay()
is called every frame (more than once probably). Last, the first frame after the collision ends (ie they no longer occupy the same space), the OnTriggerExit()
method is called only once.
If after the collision ends, and the objects separated, they collide again, then all three methods will be called again in the same order, regardless of the previous collision.
okay, thank you, i just couldnt see because i had it collapsing in the console
Thanks a lot, i was looking for an example for using a boolean to toggle with collider, this will help me a lot, thanks :)
Follow this Question
Related Questions
collision wont work 1 Answer
Best practice for OnTriggerEnter detection 1 Answer
Collision not working 3 Answers
Detecting Trigger Collision for Mecanim Animator 0 Answers
Collision detection not working properly with 2D sprites 1 Answer