How do I add an object next to a moving object?

In the snippet below, I place two red squares next to each other. You can see there is no gap between them.

If I try to do the same thing with moving objects, there is a slight gap. What’s the right way to do this?

phaser-side-by-side-question2

<!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,
      physics: { default: 'arcade' },
      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.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>

:wave:

yellow2 = this.add.rectangle(yellow.body.x + 100 /* etc */);
1 Like