Tutorials & Examples

From SolarStrike wiki
Jump to: navigation, search

Timing

There are two different methods to timing out various tasks:

1) Keep track of how much time should elapse between two points and continually remove the difference (we'll call this "runtime")

2) Keep track of timetstamps between the start/stop time and check when the stop time exceeds our target elapsed time (we'll call this "realtime")


In method 1 ("runtime"), we might want to trigger some statement after 3 seconds. To do so, we can simply set a variable to 3, then subtract the delta time each frame until it reaches zero. Once it hits zero, we know that 3 seconds have elapsed.

-- Initialize our timeLeft to 3
function macro.init()
  timeLeft = 3;
end

function macro.main(dt)
  -- Subtract how much time has elapsed since last frame
  timeLeft = timeLeft - dt;

  -- Check if it is triggered
  if( timeLeft < 0 ) then
    print("3 seconds have elapsed.");
    timeLeft = 3; -- Now reset it
  end
end


In method 2 ("realtime"), you instead keep track of an actual timestamp and use it for comparison. That is, you record the start timestamp and then continually check if now - start is greater than target elapsed time.

-- Initialize our timestamp
function macro.init()
  startTime = time.now()
end

function macro.main(dt)
  if( time.diff(startTime) > 3 ) then
    print("3 seconds have elapsed.");
    startTime = time.now(); -- Now reset it
  end
end


So why two different methods? Method 2 ("realtime") directly compares two timestamps; this is like setting a date on a calendar. The problem with this is that real time elapses whether or not the script is running. You might want to temporarily pause your script and resume it later, but time has still elapsed and will be counted towards this type of timer.

Method 1 ("runtime") keeps a running count of how much time has elapsed between frames where the script wants to track it. This gives you more control in two ways. First, you can "pause" this type of timer easily. Second, you can manipulate the speed of time that gets taken into account. For example, in a game where you are tracking a skill cooldown that lasts 10 seconds, that timer might not continue to tick down when your character is stunned. Or, the player may gain a status effect that increases or decreases their skill cooldowns by some percent, such as "bullet time" where everything goes into slow motion.