You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Phaser中正确实现新对象无间隙紧邻放置在运动物体旁

问题原因

出现间隙的核心原因是两点:

  1. Phaser默认使用浮点型坐标计算物理位移,运动物体的坐标会出现非整数值,浏览器对非整数坐标的图形做亚像素渲染时,相邻边缘会产生抗锯齿效果,看起来就像有微小间隙。
  2. 你在update生命周期中创建第二个黄色方块的时机是当前帧物理更新完成后,若坐标计算没有和物理体的实际位置严格对齐,加上浮点精度的微小累积误差,会让两个运动物体的间距逐渐出现偏差。

解决方法

按以下步骤修改即可消除间隙:

  • 游戏全局配置开启roundPixels: true,强制所有渲染坐标取整,避免亚像素渲染问题
  • 创建第二个黄色方块时,直接基于前一个方块的物理体坐标计算初始位置,保证初始对齐精度
  • 可选:固定物理引擎的时间步,减少不同帧率下的位移误差

修改后完整代码

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.min.js"></script>
  </head>
  <body>
    <script>
    var config = {
      type: Phaser.AUTO,
      width: 800,
      height: 600,
      roundPixels: true, // 新增:强制像素对齐渲染
      physics: { 
        default: 'arcade',
        arcade: {
          fixedStep: true // 可选:固定物理时间步,进一步减少误差
        }
      },
      scene: { create: create, update: update },
    };

    var game = new Phaser.Game(config);
    var red, red2, yellow, yellow2;
    const velocity = -300;

    function create() {
      red = this.add.rectangle(400, 200, 100, 100, 0xff0000).setOrigin(0, 0);
      red2 = this.add.rectangle(red.x + 100, 250, 100, 100, 0xff6666).setOrigin(0, 0);

      yellow = this.add.rectangle(400, 400, 100, 100, 0xffff00).setOrigin(0, 0);
      this.physics.add.existing(yellow);
      yellow.body.velocity.x = velocity;
    }

    function update() {
      if (yellow.x < 200 && !yellow2) {
        // 修改:基于黄色方块的物理体坐标计算第二个方块的初始位置
        yellow2 = this.add.rectangle(yellow.body.x + 100, 450, 100, 100, 0xffff66).setOrigin(0, 0);
        this.physics.add.existing(yellow2);
        yellow2.body.velocity.x = velocity;
      }
      if (yellow.x < -200) {
        this.scene.restart();
        yellow2 = undefined;
      }
    }
    </script>
  </body>
</html>

内容的提问来源于stack exchange,提问作者Pandu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:24:05