What’s the best way to detect a trigger collision with an object that resides on a location for x number of seconds?
For example:
I want to have a secret in my game where if the player stays in a certain spot for 5 seconds, something then happens. I need to know they are standing there and keep track of that time.
Start a timer in OnTriggerEnter and check it in OnTriggerStay.
–Eric
I’m not sure what I’m doing wrong here. This is the behavior I’m seeing and it’s not quite right.
Player enters the collider:
Bool is triggered, recognizing there is a player
Timer starts
Timer end
When the player starts moving again, it triggers the “SPAWN CHEST”
Exit triggers as normal
Here’s the script I’m working on:
It should be noted that I’m using transform.translate for movement, I’m wondering if when I stop the player if the is Kinematic is getting triggered?
Would that prevent OnTriggerStay from executing?
using UnityEngine;
using System.Collections;
public class SecretChair : MonoBehaviour
{
// Item we want to spawn
public GameObject secretItem;
// How long the player needs to stay at location
public float timerCountDown = 5.0f;
// Is the player currently at location
bool isPlayerColliding = false;
void Update()
{
// Collision timer
if (isPlayerColliding == true)
{
timerCountDown -= Time.deltaTime;
if (timerCountDown < 0)
{
timerCountDown = 0;
}
}
Debug.Log(isPlayerColliding);
}
// Start the collision timer when player enters
void OnTriggerEnter2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
Debug.Log("Player Entered");
isPlayerColliding = true;
}
}
// Check if the player is still at location, if they are spawn our secret item
void OnTriggerStay2D(Collider2D other)
{
if(other.gameObject.tag == "Player" && isPlayerColliding == true)
{
Debug.Log("Countdown not done yet");
if(timerCountDown <= 0)
{
Debug.Log("SPAWN CHEST");
}
}
}
// If the player is not colliding reset our timer
void OnTriggerExit2D(Collider2D other)
{
if(other.gameObject.tag == "Player")
{
Debug.Log("Player Exited");
isPlayerColliding = false;
}
}
}
Just did a sanity check, is Kinematic is not being turned on when I stop the character.
So I figured this out, it was the sleep option on my rigidbody2d. Apparently it was falling asleep.