I want to do the following:
if I press “A” my character performs task 1.
if I release “A”, two things may happen:
-if i press “D” before up to X seconds (so in a range between 0 and X seconds after releasing “A”), then my char performs task 2.
-if X seconds have passed without the key “D” being pressed, then my char performs task 3.
How do you code this? I have problems dealing with time on code.
You already wrote a functioning pseudo code logic, so what exactly you need help with?
Usually when you want to do something with time and measure how much time has elapsed, you store a reference to the current time, and then when you check the elapsed time, you just
subtract the time you stored from the current time.
But this pattern works quite ok for simple scenarios. But if you’re building something more complex like some combo system for a fighting game, then it needs more thinking etc.
Don’t forget to reset the timer after you have performed the time-dependent tasks.
Here’s some code I wrote quickly, it might work as a template, you need to change a few things for sure.
public class InputBehavior : MonoBehaviour
{
float timer;
float delay = 2f;
void Update()
{
// If player presses A key,
if (Input.GetKeyDown(KeyCode.A))
{
Debug.Log("Player pressed A.");
// Store current time.
timer = Time.time;
// Perform initial task.
PerformTask1();
}
// Every frame, calculate elapsed time.
float timeElapsed = Time.time - timer;
// If player presses D down and timer is less than or equal to the set delay,
if (Input.GetKeyDown(KeyCode.D) && timeElapsed <= delay)
{
Debug.Log("Player pressed D in time. time elapsed: " + timeElapsed);
PerformTask2();
}
// Else if player was too late, call another method.
else if (Input.GetKeyDown(KeyCode.D) && timeElapsed > delay)
{
Debug.Log("Player pressed D too late. time elapsed: " + timeElapsed);
PerformTask3();
}
}
void PerformTask1()
{
Debug.Log("Perform task 1.");
// Do not reset timer, as we wait for next input in the sequence.
}
void PerformTask2()
{
Debug.Log("Perform task 2.");
// Reset timer.
timer = 0;
}
void PerformTask3()
{
Debug.Log("Perform task 3.");
// Reset timer.
timer = 0;
}
}