patternMinor
Tick module for the game
Viewed 0 times
themodulegamefortick
Problem
I tried to look up and suck in most of the information about optimizing this operation and this is what I came up with. As it's pretty much core of the game, I really would like to have it performant as much as I can. I would appreciate if someone can take a look at this and possibly find weak spots.
Note: I am using Browserify, hence that
I am thinking about removing that
Note: I am using Browserify, hence that
module.exports. Don't get confused, it is supposed to run in the browser.module.exports = (tickModule, app) ->
# Function to retrieve current timestamp, hopefully using window.performance object
getTime = if (perf = window.performance)? then -> perf.now() else Date.now
# Store the reference so there is no need for scope lookup in every tick
raf = window.requestAnimationFrame
# Indicates if module is running
running = false
# Holds identifier for cancelAnimationFrame call
requestId = null
# Timestamp of the last run of the tick
previous = 0
# Run the tick loop
tick = ->
return unless running
# Request frame and store identifier
requestId = raf tick
# Retrieve current timestamp
timestamp = getTime()
# Calculate number of seconds from last tick
delta = (timestamp - previous) * 0.001
# Store the timestamp for the next round
previous = timestamp
# Emit event with delta
app.land.emit 'tick', delta, timestamp
# Start ticking when module start
tickModule.addInitializer ->
previous = getTime()
running = true
tick()
# Stop ticking when module stops
tickModule.addFinalizer ->
running = false
window.cancelAnimationFrame requestIdI am thinking about removing that
requestId and running, since I am not really planning to stop the ticking once it starts. It was made merely like nice gesture, but it's not that useful for the game I suppose.Solution
Do you really need a comment above every line? There are a few good comments like
Secondly, your function alias
Finally, I'd recommend renaming
# Function to retrieve current timestamp, hopefully using window.performance object, but comments like # Indicates if module is running are really not useful. They add no value to the code itself, and can be removed. Preferably, you should only be using comments when parts of the code are unclear.Secondly, your function alias
raf is fairly unclear. I'd recommend renaming it to something like requestFrame. Also, if you're creating aliases for functions like this, I'd also recommend creating one for window.cancelAnimationFrame, and other functions like this.Finally, I'd recommend renaming
tick to something like tickLoop, like how it's described in the comment above it.Context
StackExchange Code Review Q#56945, answer score: 3
Revisions (0)
No revisions yet.