/** * Control 场景类 * * 允许用户控制角色 */ import BreatheLife from './BreatheLife.js' import Joystick from './Joystick.js' export default class Control extends BreatheLife { constructor(sceneKey = 'Control') { // 场景相关 super(sceneKey) this.nextScene = 'InfoBar' } preload() { super.preload() } create() { super.create() // 设置 Control 场景的目标角色数量 this.targetCount = 2 // 目标角色数量 // 初始化输入事件 this.initInput() // 添加随机NPC this.addRandomNPCs() } // Control 场景不再需要覆盖 initSceneTransition 方法 // 数组初始化由父类 BreatheLife.create() 中的 initSceneTransition() 完成 // targetCount 通过在 create() 中直接设置来覆盖 initInput() { // 移除父类的输入事件监听器,避免重复监听 super.removeListener() // 监听鼠标点击事件 this.input.on('pointerdown', () => { // 获取点击位置的坐标 const { x, y } = this.input.activePointer this.handleClick(x, y) }) // 添加摇杆 this.addJoystick() } /** * 处理点击事件 * @param {number} x - 点击的 x 坐标 * @param {number} y - 点击的 y 坐标 */ handleClick(x, y) { // 获取点击位置的精灵 const clickedSprite = this.getClickedSprite(x, y) console.log("点击到的精灵:", clickedSprite) if (clickedSprite && this.NPCObjects.includes(clickedSprite)) { // 如果点击到了角色 this.handleSpriteClick(clickedSprite) }else { // 创建玩家可控制角色 // this.createCharacter(x, y) } } /** * 创建NPC * @param {number} x - NPC的 x 坐标 * @param {number} y - NPC的 y 坐标 */ createNPC(x, y) { // 创建一个新的角色 sprite,缩放为1倍,并设置原点为中心底部 const sprite = this.physics.add.sprite(x, y, `player1-0`).setScale(1).setOrigin(0.5, 1) sprite.setDepth(this.SpriteDepth) // 设置角色层级 this.NPCObjects.push(sprite) // 加入角色集合 this.addSpriteAnimation(sprite) // 添加角色动画 this.searchAndAddSmallGrass(sprite) // 添加搜索逻辑,自动检测最近的小草 // // 设置角色碰撞世界边界 // sprite.setCollideWorldBounds(true) } /** * 添加随机NPC */ addRandomNPCs() { // 随机生成NPC数量 const randomCount = 5 for (let i = 0; i < randomCount; i++) { // 随机间隔随机位置生成NPC const interval = Phaser.Math.Between(0, 500) this.time.delayedCall(interval, () => { const x = Phaser.Math.Between(0, this.game.config.width) const y = Phaser.Math.Between(0, this.game.config.height) this.createNPC(x, y) }) } } /** * 添加摇杆 */ addJoystick() { this.joystick = new Joystick(this, 100, this.game.config.height - 100, 50, 0x888888, 0xcccccc) this.joystick.createJoystick(this.UIDepth) // 创建并设置摇杆层级为UI层 this.joystick.listenJoystickInput() } }