::That’s a great question Liêm. In the video, the code listens to input using OnTriggerStay2D()
. Ideally, this should be moved to Update()
, because if you listen to input in OnTriggerStay2D()
, the input gets dropped if it doesn’t happen at the time frame as Update()
.
For example:
// Update is called once per frame
void Update()
{
}
private void OnTriggerStay2D(Collider2D _collision)
{
if(_collision.CompareTag("Player") && Input.GetButtonDown("Interact"))
{
interacted = true;
}
}
The logic should be reorganised so that the input is checked in Update()
instead, like this:
bool hasSeater = false;
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Interact") && hasSeater) interacted = true;
}
private void OnTriggerStay2D(Collider2D _collision)
{
if(_collision.CompareTag("Player") && Input.GetButtonDown("Interact"))
{
interacted = true;
}
}
void OnTriggerEnter2D(Collider2D _collision)
{
if(_collision.CompareTag("Player")) hasSeater = true;
}
void OnTriggerExit2D(Collider2D _collision)
{
if(_collision.CompareTag("Player")) hasSeater = false;
}
This happens because basically the physics-based OnTriggerStay2D()
is fixed — it always happens at the same time regardless of frame rate, and Update()
will change the number of times it runs depending on frame rate (and Input only gets read on Update()
.
You can read this article if you are interested in learning more: https://blog.terresquall.com/2020/08/unity-rigidbodys-interpolate-property/