Created
January 11, 2023 10:06
-
-
Save quasilyte/acda7b4e26ee4169bd3da29cba113dc8 to your computer and use it in GitHub Desktop.
Fixed timestep vs Delta time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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