Samouczek 2 — Postać, która się porusza i animuje
Rzeczy, które się poruszają, to encje (src/Entity/), tworzone przez sceny za pomocą new. Encja ma pozycję ($this->x, $this->y), prędkość (vx, vy), rozmiar, kierunek (facing) i stan (state). Traity dodają zdolności: Sprite (animacja), Gravity (spadanie), TileCollision (wiedza, czy dotykamy podłoża).
Sprite narysowany w PHP
Nie potrzeba obrazu: createTextureFromPixels() tworzy teksturę z wierszy tekstu. Każdy znak to piksel, a . jest przezroczysty.
private const SHEET = [ // 3 klatki 12 × 14: bezruch, marsz, skok
'...####........####........####.....',
'..######......######......######....',
'..##o#o#......##o#o#......##o#o#....',
// ...
];
public function __construct(Sdl $sdl, float $x, float $y)
{
$this->x = $x;
$this->y = $y;
$this->width = 10;
$this->height = 14;
if (!$sdl->hasTexture('player')) {
$sdl->createTextureFromPixels('player', self::SHEET, ['#' => '#ffd23f', 'o' => '#202020']);
}
$this->initSprite($sdl, 'player', 'idleRight');
}
Z prawdziwym arkuszem sprite'ów: $sdl->loadTexture('player', 'assets/sprites/player.png').
Animacje
Animacja to lista klatek z arkusza. Silnik wybiera animację <stan><Kierunek>: walkRight, idleLeft… reverseWalkRight używa tych samych klatek odwróconych.
protected array $animations = [
'idleRight' => ['coords' => [['x' => 0, 'y' => 0, 'w' => 12, 'h' => 14]]],
'walkRight' => ['coords' => [['x' => 12, 'y' => 0, 'w' => 12, 'h' => 14], ['x' => 0, 'y' => 0, 'w' => 12, 'h' => 14]], 'duration' => 0.12],
'jumpRight' => ['coords' => [['x' => 24, 'y' => 0, 'w' => 12, 'h' => 14]]],
'idleLeft' => 'reverseIdleRight',
'walkLeft' => 'reverseWalkRight',
'jumpLeft' => 'reverseJumpRight',
];
Poruszanie się z rozpędem
use Sprite, Gravity, TileCollision {
Sprite::update as updateSprite;
Gravity::update as updateGravity;
}
public function control(int $move, bool $jumpPressed, bool $jumpHeld, float $dt): void
{
// przyspiesza łagodnie do żądanej prędkości
$this->vx = Math::approach($this->vx, $move * 110, 900 * $dt);
if ($move !== 0) {
$this->facing = $move < 0 ? 'left' : 'right';
}
if ($jumpPressed && $this->onGround) {
$this->vy = -290;
}
if (!$jumpHeld && $this->vy < -100) {
$this->vy = -100; // przycisk puszczony wcześnie: krótszy skok
}
}
public function update(float $dt): void
{
$this->updateGravity($dt);
$this->state = !$this->onGround ? 'jump' : (abs($this->vx) > 10 ? 'walk' : 'idle');
$this->pickAnimation(); // wybiera "<state><Facing>"
$this->updateSprite($dt); // następna klatka
}
public function render(Renderer $r, float $camX = 0, float $camY = 0): void
{
$this->drawAt($r, $this->x - 1 - $camX, $this->y - $camY);
}
W scenie: $player->control($this->actions()->axis('left', 'right'), $this->actions()->isPressed('jump'), $this->actions()->isHeld('jump'), $dt), a potem $player->update($dt). Poruszanie się względem ścian i podłoża to zadanie systemu kolizji: samouczek 3.
Ten kod pochodzi ze szkieletu JumPHP (bin/jumphp new): src/Entity/Player.php.