ES

Tutorial 2 — Un personaje que se mueve y se anima

Las cosas que se mueven son entidades (src/Entity/), creadas con new por las escenas. Una entidad tiene una posición ($this->x, $this->y), una velocidad (vx, vy), un tamaño, una dirección (facing) y un estado (state). Los traits añaden capacidades: Sprite (la animación), Gravity (la caída), TileCollision (saber si se toca el suelo).

Un sprite dibujado en PHP

No hace falta ninguna imagen: createTextureFromPixels() fabrica una textura a partir de líneas de texto. Cada carácter es un píxel y . es transparente.

private const SHEET = [            // 3 imágenes de 12 × 14: quieto, caminando, 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 una hoja de sprites real: $sdl->loadTexture('player', 'assets/sprites/player.png').

Las animaciones

Una animación es una lista de imágenes de la hoja. El motor elige la animación <estado><Dirección>: walkRight, idleLeft… reverseWalkRight reutiliza las imágenes volteadas.

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

Moverse con inercia

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 hacia la velocidad deseada
    $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ón soltado pronto: salto más corto
    }
}

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

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

En la escena: $player->control($this->actions()->axis('left', 'right'), $this->actions()->isPressed('jump'), $this->actions()->isHeld('jump'), $dt) y después $player->update($dt). El movimiento contra las paredes y el suelo es trabajo del sistema de colisiones: tutorial 3.

Este código es el del esqueleto de JumPHP (bin/jumphp new): src/Entity/Player.php.