Phaser.js 物理群组中可拖拽子对象的实现教程

Phaser.js 物理群组中可拖拽子对象的实现教程

本教程详细介绍了如何在 Phaser.js 框架中使用 Arcade 物理引擎,实现物理群组中每个子对象独立拖拽的功能,同时保持它们与其他群组成员或世界边界的碰撞检测。通过配置交互性、监听指针事件(pointerdown、drag、dragend),并结合物理碰撞回调,确保对象在拖拽过程中能正确响应用户输入,并在释放后继续其物理行为,为游戏开发提供灵活的交互性解决方案。

在 Phaser.js 游戏开发中,我们经常需要管理一组具有相同物理属性的游戏对象,通常通过物理群组(Physics Group)来实现。然而,当需求涉及到让群组中的每个子对象都能被独立拖拽,同时又要保持其物理特性(如碰撞检测)时,可能会遇到一些挑战。本教程将详细讲解如何在 Phaser.js 的 Arcade 物理引擎下,实现这一功能。

核心原理

实现物理群组中可拖拽子对象的关键在于以下几点:

  1. 使单个子对象可交互: 每个需要被拖拽的子对象都必须设置为可交互的。
  2. 监听拖拽相关事件: 利用 Phaser.js 提供的输入事件来处理拖拽的开始、进行和结束。
  3. 管理被选中的对象: 在拖拽过程中,需要一个机制来识别当前正在被拖拽的特定对象。

实现步骤详解

1. 初始化 Phaser 游戏与场景

首先,我们需要设置一个基本的 Phaser 游戏配置,并创建一个场景。确保将物理引擎设置为 arcade。

document.body.style = 'margin:0;'; // 移除默认边距,使画布全屏  var config = {     type: Phaser.AUTO, // 自动选择渲染器 (WebGL 或 canvas)     width: 536,     height: 183,     physics: {         default: 'arcade', // 使用 Arcade 物理引擎         arcade: {                         gravity: { y: 0 }, // 设置重力为0,或根据需要调整         }     },     scene: { create } // 定义场景的 create 方法 };   new Phaser.Game(config); // 创建游戏实例

2. 创建物理群组与子对象

在 create 方法中,我们将创建一个物理群组,并向其中添加多个子对象。这些子对象可以是预加载的图片纹理,也可以是动态生成的图形纹理。

function create () {     // 添加一个文本提示     this.add.text(10,10, 'Drag&Drop Demo')         .setScale(1.5)         .setOrigin(0)         .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});      // 生成一个简单的三角形纹理供子对象使用     let graphics  = this.make.graphics();     graphics.fillStyle(0xffffff); // 白色填充     graphics.fillTriangle(0, 0, 10, 5, 0, 10); // 绘制一个三角形     graphics.generateTexture('img', 10, 10); // 生成名为 'img' 的纹理      // 创建一个物理群组,并添加重复的子对象     this.photons = this.physics.add.group({       key: "img", // 使用 'img' 纹理       repeat: 2,  // 重复2次,所以总共有3个子对象 (1个初始 + 2个重复)       setXY: { x: 50, y: 50, stepX: 32 }, // 设置初始位置和X轴步进     });      // 用于存储当前被拖拽的子对象     this.selectedPhoton = null;  }

3. 配置子对象的物理属性与交互性

接下来,我们需要遍历群组中的每个子对象,为其设置物理属性(如弹跳、速度、世界边界碰撞)并使其可交互。

Phaser.js 物理群组中可拖拽子对象的实现教程

图可丽批量抠图

ai技术提高数据生产力,让美好事物更容易被发现

Phaser.js 物理群组中可拖拽子对象的实现教程 26

查看详情 Phaser.js 物理群组中可拖拽子对象的实现教程

关键点:

  • 使用 child.setInteractive({ draggable: true }) 来一步到位地设置对象的交互性并使其可拖拽。这比单独调用 setInteractive() 和 setDraggable() 更简洁。
  • 在 pointerdown 事件中,将当前被点击的子对象保存到 this.selectedPhoton 变量中,以便后续的 drag 和 dragend 事件能够识别和操作它。
    this.photons.children.iterate(function (child) {       child.body.bounce.set(1); // 设置弹跳系数为1 (完全反弹)       child.setVelocity(Phaser.Math.Between(0, 100),30); // 设置随机初始速度       let initialAngle = (new Phaser.Math.Vector2(child.body.velocity)).angle();       child.setRotation(initialAngle); // 根据速度方向设置初始旋转       child.body.collideWorldBounds = true; // 开启世界边界碰撞       child.body.onWorldBounds = true; // 开启世界边界碰撞事件        child.setInteractive({ draggable: true }); // 设置为可交互并可拖拽       child.setScale(2); // 放大显示        // 监听子对象的 pointerdown 事件       child.on('pointerdown',  () => {         this.selectedPhoton = child; // 当鼠标按下时,保存当前被点击的子对象       });      }, this); // <-- 确保传递正确的上下文 (this)

4. 处理全局拖拽事件

drag 和 dragend 事件不是在单个游戏对象上监听的,而是在 Phaser 的 InputPlugin 上监听。这使得我们可以在拖拽过程中统一处理所有可拖拽对象的行为。

    // 监听全局的 drag 事件     this.input.on('drag', pointer =>  {         if(this.selectedPhoton){           // 如果有被选中的子对象,更新其位置到指针位置           this.selectedPhoton.setPosition( pointer.x, pointer.y);         }     });      // 监听全局的 dragend 事件     this.input.on('dragend', pointer =>  {         if(this.selectedPhoton){             // 拖拽结束时,再次更新位置并清除 selectedPhoton             this.selectedPhoton.setPosition( pointer.x, pointer.y);             this.selectedPhoton = null; // 清除选中状态         }     });

5. 处理物理碰撞与视觉更新

为了使子对象在碰撞后能正确地更新其视觉方向,我们需要监听世界边界碰撞和群组内部碰撞事件。

    // 监听世界边界碰撞事件,更新对象旋转     this.physics.world.on('worldbounds', (photonBody) => {         let newAngle = (new Phaser.Math.Vector2(photonBody.velocity)).angle();         photonBody.gameObject.setRotation(newAngle);     });      // 监听群组内部碰撞事件,更新两个碰撞对象的旋转     this.physics.add.collider(this.photons, this.photons, (p1, p2) => {         let newAngle = (new Phaser.Math.Vector2(p1.body.velocity)).angle();         p1.setRotation(newAngle);         newAngle = (new Phaser.Math.Vector2(p2.body.velocity)).angle();         p2.setRotation(newAngle);     });

完整示例代码

将上述所有代码片段整合,并包含必要的 html 引用,即可得到一个完整的可运行示例。

<!DOCTYPE html> <html> <head>     <title>Phaser.js Physics Group Draggable Children</title>     <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>     <style>         body { margin: 0; }     </style> </head> <body>  <script> document.body.style = 'margin:0;';  var config = {     type: Phaser.AUTO,     width: 536,     height: 183,     physics: {         default: 'arcade',         arcade: {                         gravity: { y: 0 },         }     },     scene: { create } };   function create () {     this.add.text(10,10, 'Drag&Drop Demo')         .setScale(1.5)         .setOrigin(0)         .setStyle({fontStyle: 'bold', fontFamily: 'Arial'});      let graphics  = this.make.graphics();     graphics.fillStyle(0xffffff);     graphics.fillTriangle(0, 0, 10, 5, 0, 10);     graphics.generateTexture('img', 10, 10);      this.photons = this.physics.add.group({       key: "img",       repeat: 2,       setXY: { x: 50, y: 50, stepX: 32 },     });      this.photons.children.iterate(function (child) {       child.body.bounce.set(1);       child.setVelocity(Phaser.Math.Between(0, 100),30);       let initialAngle = (new Phaser.Math.Vector2(child.body.velocity)).angle();       child.setRotation(initialAngle);       child.body.collideWorldBounds = true;       child.body.onWorldBounds = true;        child.setInteractive({ draggable: true });       child.setScale(2);        child.on('pointerdown',  () => {         this.selectedPhoton = child;       });      }, this); // <-- don't forget to pass the context      this.input.on('drag', pointer =>  {         if(this.selectedPhoton){           this.selectedPhoton.setPosition( pointer.x, pointer.y);         }     });      this.input.on('dragend', pointer =>  {         if(this.selectedPhoton){             this.selectedPhoton.setPosition( pointer.x, pointer.y);             this.selectedPhoton = null         }     })      this.physics.world.on('worldbounds', (photonBody) => {         let newAngle = (new Phaser.Math.Vector2(photonBody.velocity)).angle();         photonBody.gameObject.setRotation(newAngle);     });      this.physics.add.collider(this.photons, this.photons, (p1, p2) => {         let newAngle = (new Phaser.Math.Vector2(p1.body.velocity)).angle();         p1.setRotation(newAngle);         newAngle = (new Phaser.Math.Vector2(p2.body.velocity)).angle();         p2.setRotation(newAngle);     }); }  new Phaser.Game(config); </script>  </body> </html>

注意事项与总结

  • 上下文绑定: 在 this.photons.children.iterate 方法中,务必将 this 作为第二个参数传递,以确保回调函数内部的 this 正确指向场景对象。或者,使用箭头函数 (() => {}) 来自动绑定 this 上下文。
  • 拖拽与物理冲突: 当一个物理对象被拖拽时,它的物理位置会被手动设置。这意味着在拖拽期间,物理引擎可能不会完全控制其位置,但一旦拖拽结束,对象将恢复受物理引擎控制。本示例中,拖拽只是简单地设置了对象的位置,并没有禁用其物理体,因此在拖拽时,对象仍会响应碰撞,但其位置会优先被指针控制。
  • Matter.js 与 Arcade Physics: 本教程专注于 Arcade Physics。如果使用 Matter.js,拖拽实现方式会有所不同,通常会涉及创建约束(constraints)来模拟拖拽行为。
  • 性能优化 对于大量可拖拽对象,频繁的 setPosition 操作可能会有性能开销。在更复杂的场景中,可以考虑在拖拽开始时禁用对象的物理体,并在拖拽结束时重新启用,或者使用更高级的拖拽插件。

通过上述步骤,我们成功实现了在 Phaser.js 物理群组中对单个子对象进行独立拖拽的功能,同时保持了其物理特性。这种方法为开发交互性丰富的游戏提供了坚实的基础。

上一篇
下一篇
text=ZqhQzanResources