Alterna · учебный материал

Playing mechanics

44.1.: Game cycle, motion, delta time and impact in the browser Canvas shell.

Что в этом материале

Содержание и основные понятия

The reliable mechanics divides the data and the image. The player's coordinate, speed, walls and collected objects exist in the model; Canvas only shows their current state.
algorithm
coordinates
Canvas shell
01
Why Do You Need a Delta Time
The frequency changes: one browser can draw 60 frames per second, the other less, so the movement isn't "three pixels per frame" but the formula.
new_x = x + speed × delta
where
delta
- Last time in seconds.
скорость = 150 пикселей/сек
delta = 0.016 сек
смещение ≈ 2.4 пикселя
input
which keys are held
update
new coordinates and checks
draw
Current status on Canvas
02
Clash without magic
Player - Circle
For a player, a center is enough.
(x, y)
and radius
r
It's convenient for free movement across the plane.
Wall - rectangle
For the wall, the left upper corner, width, and height are retained.
Order is important
First compute the intended position, then check the walls, and only if you don't cross new coordinates, so the player doesn't end up inside the barrier.
03
Tact games
The start and the same stroke give different ways to observe the same algorithm.
↻
Speed and personnel
04
Game and its source code
The demonstration below doesn't hide the algorithm. Change speed, boundaries, position of crystals, or rules of victory, press "start", then run the arrows or WASD directly to Canvas.
init()
Creates a fortune,
update()
computes the shift through
dt
And checks the walls,
draw()
He's building a frame. Try to replace the speed.
240
pixels per second per
360
add a wall or change the radius of impact.
Code Editor uploads...

Structural map of textbooks