用途
本技能用于在 Phaser 4 中使用 Arcade Physics(街机物理)引擎。Arcade Physics 是一套轻量、高效的 2D 物理系统,适合平台跳跃、弹球、射击等对物理精度要求不高的游戏场景。技能覆盖物理启用、速度、加速度、重力、碰撞、重叠、世界边界、物理体属性和碰撞分类等主题。
主要能力
- 启用物理:在 GameConfig 的
physics字段中设置default: 'arcade',并可配置重力、调试等参数。 - 创建物理对象:通过
this.physics.add.sprite()、image()、staticSprite()、staticImage()、group()、staticGroup()创建带动态体或静态体的对象,也可用this.physics.add.existing()为已有对象添加物理体。 - 运动控制:设置速度(velocity)、加速度(acceleration)、阻力(drag)、每体独立重力(gravity)、弹跳(bounce)、最大速度(maxVelocity/maxSpeed)、质量(mass)等。
- 碰撞与重叠:使用持久碰撞器
this.physics.add.collider()/overlap()每帧自动检测,或使用一次性检测this.physics.collide()/overlap()。支持 processCallback 条件过滤和组内自碰撞。 - 世界边界:通过
this.physics.world.setBounds()设置边界尺寸与各边碰撞开关,支持每体自定义边界矩形和边界反弹。 - 物理体属性:设置尺寸、偏移、圆形体、不可移动、可推动、滑动因子、质量、按方向碰撞开关等。
- 碰撞分类:使用位掩码(最多 32 类)过滤哪些物理体之间可以碰撞,支持
nextCategory()、setCollisionCategory()、setCollidesWith()等方法。 - 事件系统:监听
collide、overlap、worldbounds、tilecollide、tileoverlap、worldstep、pause、resume等事件(需在物理体上开启对应开关)。
使用方式
在 GameConfig 中启用 Arcade Physics:
const config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
},
scene: GameScene
};
在场景中创建物理精灵并注册碰撞器:
this.player = this.physics.add.sprite(100, 300, 'player');
this.player.setCollideWorldBounds(true);
this.player.setBounce(0.2);
this.platforms = this.physics.add.staticGroup();
this.platforms.create(400, 568, 'ground').setScale(2).refreshBody();
this.physics.add.collider(this.player, this.platforms);
在 update 中控制速度:
if (this.cursors.left.isDown) {
this.player.setVelocityX(-160);
} else if (this.cursors.right.isDown) {
this.player.setVelocityX(160);
} else {
this.player.setVelocityX(0);
}
适用场景
- 平台跳跃游戏中的角色移动、重力、地面碰撞。
- 射击游戏中子弹与敌人的重叠检测。
- 弹球类游戏中的反弹与碰撞。
- 需要简单高效 2D 物理模拟的 Phaser 4 项目。
限制
- Arcade Physics 是简化的物理系统,不提供真实物理模拟(如旋转碰撞、复杂形状碰撞),复杂物理需求应使用 Matter.js 等引擎。
- 静态体在修改位置或缩放后需调用
refreshBody()或body.reset()同步。 - 事件需在物理体上显式开启(如
body.onCollide = true)才会触发。 - 碰撞分类最多 32 类。
- 当动态体数量超过 5000 时,建议关闭 RTree 空间索引(
useTree)。
相关技能
- ../game-setup-and-config/SKILL.md
- ../sprites-and-images/SKILL.md
- ../tilemaps/SKILL.md
- ../groups-and-containers/SKILL.md
关键源码路径:src/physics/arcade/ArcadePhysics.js、World.js、Body.js、StaticBody.js、Factory.js、components/、events/。