PT

Tutorial 3 — Um jogo de plataforma: fase, colisões, câmera

Uma fase escrita em linhas

Para começar, uma fase se escreve direto no código: um caractere por tile de 16 × 16 pixels.

private const LEVEL = [
    '..........................C.C.C.........',
    '.........................=======........',
    '...P....................................',
    '#########............C......######......',
    '#########..........#####...########.....',
    '########################################',
];

$this->map = ArrayLoader::fromRows(self::LEVEL,
    legend: ['#' => 1, '=' => 2, '/' => 3, '\\' => 4],     // os tiles
    objects: ['P' => 'start', 'C' => 'coin'],                // objetos colocados na fase
    tileWidth: 16, tileset: 'generated:tiles');
$tileset = $this->map->tilesets[0];
$tileset->masks[1] = CollisionMask::oneWay();                // '=': dá para atravessar por baixo, pulando
$tileset->masks[2] = CollisionMask::slope(16, 16, 1, 16);    // '/': uma rampa

Quando o jogo crescer, desenhe as fases com o Tiled: TiledJsonLoader::load($this->engine->config->path('assets/maps/niveau1.tmj')).

As colisões

Injete os serviços no construtor da cena (eles são fornecidos automaticamente):

public function __construct(
    private TileMapRenderer $tiles,
    private CollisionSystem $collisions,
    private EntityManager $entities,
) {
}

A cada quadro, ajusta-se a velocidade e depois move-se com o sistema de colisões: ele avança pixel a pixel, para nas paredes, pousa no chão, sobe as rampas e preenche $player->onGround.

$this->player->control($move, $jump, $held, $dt);
$this->player->update($dt);
$this->collisions->move($this->player, $this->map, $dt);

Cair para fora da fase: $this->collisions->on('fell', fn () => $this->respawn()); (em enter(), depois de $this->collisions->removeAllListeners()).

As moedas

Os objetos da fase viram entidades:

$this->entities->clear();
$this->entities->register('coin', Coin::class);
$this->entities->spawnFromMap($this->map);

// em update():
$this->entities->update($dt, $this->camera);
foreach ($this->entities->overlapping($this->player->getBoundingBox()) as $entity) {
    if ($entity instanceof Coin) {
        $entity->kill();                    // removida automaticamente
        $this->coins++;
        $this->sound()->playSfx('coin');
    }
}

A câmera

$this->camera = new Camera($this->width(), $this->height());
$this->camera->setBounds(0, 0, $this->map->pixelWidth(), $this->map->pixelHeight());
$this->camera->follow($this->player, 0.15, 0.3);    // uma zona morta no centro da tela

// update(): $this->camera->update($dt);
// render(): desenha-se tudo deslocado pela câmera
$cx = $this->camera->getX();
$cy = $this->camera->getY();
$this->tiles->renderBackground($r, $this->map, $cx, $cy, $this->time);
$this->entities->render($r, $this->camera);
$this->player->render($r, $cx, $cy);
$this->tiles->renderForeground($r, $this->map, $cx, $cy, $this->time);

$this->camera->shake(4, 0.3) faz a tela tremer. O jogo completo é o esqueleto do JumPHP (src/Scene/PlayScene.php): bin/jumphp new meu-jogo entrega-o a você, pronto para modificar.