PT

Tutorial 2 — Um personagem que se move e se anima

As coisas que se movem são entidades (src/Entity/), criadas com new pelas cenas. Uma entidade tem uma posição ($this->x, $this->y), uma velocidade (vx, vy), um tamanho, uma direção (facing) e um estado (state). Traits acrescentam capacidades: Sprite (a animação), Gravity (a queda), TileCollision (saber se está tocando o chão).

Um sprite desenhado em PHP

Não precisa de imagem: createTextureFromPixels() fabrica uma textura a partir de linhas de texto. Cada caractere é um pixel, . é transparente.

private const SHEET = [            // 3 quadros de 12 × 14: parado, andando, pulo
    '...####........####........####.....',
    '..######......######......######....',
    '..##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');
}

Com uma folha de sprites de verdade: $sdl->loadTexture('player', 'assets/sprites/player.png').

As animações

Uma animação é uma lista de quadros da folha. O motor escolhe a animação <estado><Direção>: walkRight, idleLeft… reverseWalkRight reaproveita os quadros espelhados.

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

Mover-se com inércia

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

public function control(int $move, bool $jumpPressed, bool $jumpHeld, float $dt): void
{
    // acelera suavemente até a velocidade desejada
    $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;    // botão solto cedo: pulo mais curto
    }
}

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

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

Na cena: $player->control($this->actions()->axis('left', 'right'), $this->actions()->isPressed('jump'), $this->actions()->isHeld('jump'), $dt) e depois $player->update($dt). O movimento contra paredes e chão é trabalho do sistema de colisões: tutorial 3.

Este código é o do esqueleto do JumPHP (bin/jumphp new): src/Entity/Player.php.