Skip to content

Instantly share code, notes, and snippets.

@quasilyte
Created January 11, 2023 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quasilyte/acda7b4e26ee4169bd3da29cba113dc8 to your computer and use it in GitHub Desktop.
Save quasilyte/acda7b4e26ee4169bd3da29cba113dc8 to your computer and use it in GitHub Desktop.
Fixed timestep vs Delta time
package main
import (
"fmt"
"log"
"strings"
"time"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
)
func main() {
ebiten.SetWindowSize(640, 480)
ebiten.SetWindowTitle("Slow Game")
if err := ebiten.RunGame(&Game{useDelta: false, prevTime: time.Now()}); err != nil {
log.Fatal(err)
}
}
type Game struct {
// useDelta selects the time computation strategy.
// false - rely on the fixed TPS rate.
// true - compute the frame delta manually.
useDelta bool
prevTime time.Time
timer time.Duration
}
func (g *Game) timeDelta() time.Duration {
if g.useDelta {
// Calculating a time delta manually.
now := time.Now()
timeDelta := now.Sub(g.prevTime)
g.prevTime = now
return timeDelta
}
// Relying on a fact that TPS rate is constant.
// 60 TPS is a default.
return time.Second / 60
}
func (g *Game) Update() error {
g.timer += g.timeDelta()
heavyWork()
return nil
}
func (g *Game) Draw(screen *ebiten.Image) {
ebitenutil.DebugPrint(screen, fmt.Sprintf("TPS: %f\nFPS: %f\nElapsed: %s", ebiten.CurrentTPS(), ebiten.CurrentFPS(), g.timer))
}
func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
return 640, 480
}
func heavyWork() {
// Do something that wastes CPU cycles.
for i := 0; i < 2000; i++ {
slice := make([]string, 100)
for j := range slice {
slice[j] = strings.Repeat("s", j)
}
res := ""
for _, part := range slice {
res += part
}
sink = res
}
}
var sink interface{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment