Hello,
I’m fairly new to game development and the patterns that come along with it. I have Xbox 360 controller vibration working, but I’m curious how I would vibrate for ‘x’ milliseconds then turn it off?
Just looking for a psuedo-example; Assuming this is done in an Update() method, I’d think it has to cache off the time at the start of the vibration, and then take a delta frame by frame until a duration has been hit, then perform my turn-off-vibration logic.
I guess the time management is the pattern I’d like to see an example of.
Thanks!
The first thing to remember is that Update runs every frame, so no time keeping can occur within the update function itself. With that in mind, you have two basic approaches.
One is to use a coroutine, triggered from the Update function, which can then wait for an arbitrary amount of time then perform an action.
function Update()
{
if (action)
Vibration();
}
function Vibration()
{
vibrate on
Yield WaitForSeconds(0.25);
vibrate off
}
The other is to have a float variable that lives outside of the function that can track time passed. So when the vibration is triggered, set the variable, and each update you subtract Time.deltaTime from it so you know when to turn the vibration off.
private var vibrateTimer : float = 0.0;
function Update()
{
if (action)
{
vibrate on
vibrateTimer = 0.25;
}
if (vibrateTimer > 0.0)
{
vibrateTimer -= Time.deltaTime;
if (vibrateTimer <= 0.0)
{
vibrate off
}
}
}
Depending on what triggers the vibration, there is a potential flaw with the coroutine approach. If the action can be spammed (a second vibration can be triggered before the first finishes) they will overlap and several coroutines will be running at the same time. The first one to finish will kill the vibration, even though a new vibration might have just been started. Meanwhile, the second case will just prolong the vibration (each press will just reset the timer) It’s all about what you’re doing and what behaviour is desirable.