Посібник 2 — Персонаж, що рухається й анімується
Те, що рухається, — це сутності (src/Entity/), які сцени створюють через new. Сутність має
позицію ($this->x, $this->y), швидкість (vx, vy), розмір, напрямок (facing) і стан
(state). Трейти додають можливості: Sprite (анімація), Gravity (падіння),
TileCollision (знати, чи торкаємося землі).
Спрайт, намальований на PHP
Зображення не потрібне: createTextureFromPixels() створює текстуру з рядків тексту. Кожен
символ — піксель, . — прозорий.
private const SHEET = [ // 3 кадри 12 × 14: стоїть, іде, стрибає
'...####........####........####.....',
'..######......######......######....',
'..##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');
}
Зі справжнім аркушем спрайтів: $sdl->loadTexture('player', 'assets/sprites/player.png').
Анімації
Анімація — це список кадрів аркуша. Рушій вибирає анімацію <стан><Напрямок>:
walkRight, idleLeft… reverseWalkRight повторно використовує віддзеркалені кадри.
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',
];
Рух з інерцією
use Sprite, Gravity, TileCollision {
Sprite::update as updateSprite;
Gravity::update as updateGravity;
}
public function control(int $move, bool $jumpPressed, bool $jumpHeld, float $dt): void
{
// плавно розганяється до бажаної швидкості
$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; // кнопку відпущено рано: стрибок коротший
}
}
public function update(float $dt): void
{
$this->updateGravity($dt);
$this->state = !$this->onGround ? 'jump' : (abs($this->vx) > 10 ? 'walk' : 'idle');
$this->pickAnimation(); // вибирає "<state><Facing>"
$this->updateSprite($dt); // наступний кадр
}
public function render(Renderer $r, float $camX = 0, float $camY = 0): void
{
$this->drawAt($r, $this->x - 1 - $camX, $this->y - $camY);
}
У сцені: $player->control($this->actions()->axis('left', 'right'), $this->actions()->isPressed('jump'), $this->actions()->isHeld('jump'), $dt), потім $player->update($dt). Рух відносно стін і землі —
робота системи зіткнень: посібник 3.
Цей код узято з шаблону JumPHP (bin/jumphp new): src/Entity/Player.php.