Tilemaps and collisions

Hi, I am just starting out with tilemaps and had some questions.

Where I am, at the moment:

  • I have a tilemap and a character png.
  • I added the tilemap with two layers, background and ground.
  • The ground layer has collisions set using indexes.
  • I have added collision debug graphics to the tile layer

The player collides just fine and falls off if I go too far but my 2 problems are:

  1. I can slide my player back on the ledge
  2. If I slide back in too late I notice my player actually isn’t colliding with the side of the wall.

Check the gif below:
(The yellow platform shows the debug collidingTileColor)
trailing-collisions

export default class MainScene extends Phaser.Scene {
  private readonly movementSpeed = 4;

  private cursors: Phaser.Types.Input.Keyboard.CursorKeys;

  private player: Phaser.Types.Physics.Arcade.SpriteWithDynamicBody;
  private ground: Phaser.Tilemaps.TilemapLayer;

  constructor() {
    super({ key: 'MainScene' });
  }

  create() {
    const map = this.make.tilemap({ key: 'map' });
    const tileset = map.addTilesetImage('level1', 'demo-tiles');
    
    map.createLayer('background', tileset, 0, 0);

    this.ground = map.createLayer('ground', tileset, 0, 0);
    this.player = this.physics.add.sprite(120, 70, 'player');

    this.ground.setCollision([9, 10, 10, 10, 11, 11, 11, 12]);

    this.physics.add.collider(this.ground, this.player, () => {});

    this.cursors = this.input.keyboard.createCursorKeys();

    this.cameras.main.startFollow(this.player);
    this.cameras.main.setZoom(1.2);

    this.addDebugConfig();
  }

  update() {
    if (this.cursors.left.isDown) {
      this.player.setX(this.player.x - this.movementSpeed);
    } else if (this.cursors.right.isDown) {
      this.player.setX(this.player.x + this.movementSpeed);
    }
  }

  addDebugConfig(): void {
    const debugGraphics = this.add.graphics().setAlpha(0.7);
    this.ground.renderDebug(debugGraphics, {
      tileColor: null,
      collidingTileColor: new Phaser.Display.Color(243, 234, 48, 255),
    });
  }
}

Generally you should use velocity to move sprites for proper separation.

1 Like

Thank you. That fixed both of my problems! Code below. :+1:

 update() {
    if (this.cursors.left.isDown) {
      this.player.setVelocityX(-170);
    } else if (this.cursors.right.isDown) {
      this.player.setVelocityX(170);
    } else {
      this.player.setVelocityX(0);
    }
  }