教程 2 — 会移动、会动画的角色
会动的东西都是实体(src/Entity/),由场景用 new 创建。实体有位置($this->x、$this->y)、速度(vx、vy)、尺寸、朝向(facing)和状态(state)。trait 则为它增加各种能力: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。