IT

Tutorial 2 — Un personaggio che si muove e si anima

Le cose che si muovono sono entità (src/Entity/), create con new dalle scene. Un'entità ha una posizione ($this->x, $this->y), una velocità (vx, vy), una dimensione, una direzione (facing) e uno stato (state). Dei trait aggiungono capacità: Sprite (l'animazione), Gravity (la caduta), TileCollision (sapere se si tocca il suolo).

Uno sprite disegnato in PHP

Non serve nessuna immagine: createTextureFromPixels() fabbrica una texture a partire da righe di testo. Ogni carattere è un pixel, . è trasparente.

private const SHEET = [            // 3 immagini da 12 × 14: fermo, cammina, salto
    '...####........####........####.....',
    '..######......######......######....',
    '..##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');
}

Con un vero spritesheet: $sdl->loadTexture('player', 'assets/sprites/player.png').

Le animazioni

Un'animazione è un elenco di immagini dello spritesheet. Il motore sceglie l'animazione <stato><Direzione>: walkRight, idleLeft… reverseWalkRight riutilizza le immagini specchiate.

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',
];

Muoversi con lo slancio

use Sprite, Gravity, TileCollision {
    Sprite::update as updateSprite;
    Gravity::update as updateGravity;
}

public function control(int $move, bool $jumpPressed, bool $jumpHeld, float $dt): void
{
    // accelera dolcemente verso la velocità voluta
    $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;    // pulsante rilasciato presto: salto più corto
    }
}

public function update(float $dt): void
{
    $this->updateGravity($dt);
    $this->state = !$this->onGround ? 'jump' : (abs($this->vx) > 10 ? 'walk' : 'idle');
    $this->pickAnimation();      // sceglie "<state><Facing>"
    $this->updateSprite($dt);    // immagine successiva
}

public function render(Renderer $r, float $camX = 0, float $camY = 0): void
{
    $this->drawAt($r, $this->x - 1 - $camX, $this->y - $camY);
}

Nella scena: $player->control($this->actions()->axis('left', 'right'), $this->actions()->isPressed('jump'), $this->actions()->isHeld('jump'), $dt), poi $player->update($dt). Lo spostamento contro i muri e il suolo è compito del sistema di collisioni: tutorial 3.

Questo codice è quello dello scheletro di JumPHP (bin/jumphp new): src/Entity/Player.php.