Tilebase movement with tilemap collisions

I was browsing old forum and there was some discussion about the topic. However those threads were quite old, so i was thinking to ask again about this topic.

I’d like to create oldschool Ultima style game, but as a freshman i stumbled upon collisions not working when moving character by position. There is one example, which kind of fits to this: https://phaser.io/examples/v3/view/game-objects/tilemap/static/grid-movement

On the example we’re checking against tile.index.

// Tilebased movement: UP
    this.input.keyboard.on('keydown_W', (event) => {
      let tile = this.elements.getTileAtWorldXY(this.player.x, this.player.y - this.tileSize, true)

      if (tile.index === 3) {
        console.log('Blocked!')
      } else {
        this.player.y -= this.tileSize
      }

    })

I don’t know if i have done something wrong with the tilemap layer, but i have multiple indexes there, so of course i could check against them all, but is there a way i could check against whole tilemap layer?

Okay, seems that -1 tile index did the trick. Still would love to have discussion around this topic, since my implementation is not probably elegant :rofl:

// Tilebased movement: LEFT
    this.input.keyboard.on('keydown_A', (event) => {
      let tile = this.blockedLayer.getTileAtWorldXY(this.player.x - this.tileSize, this.player.y, true)

      if (tile.index !== -1) {
        console.log('Blocked!')
      } else {
        this.player.x -= this.tileSize
      }
    })
2 Likes

I’m very interested in this topic as well! :slight_smile:

1 Like

Under the default settings, -1 is indeed the index used for an empty tile. Your current solution is perfectly fine. Using a separate layer to determine which tiles should be solid can be powerful because solidity doesn’t have to be linked to what the player sees.

Assuming you’re talking about Arcade physics, a general rule of thumb is that you should only move bodies by manipulating their velocity. If you directly move a body into a solid tile, there’s no way the physics system can tell which direction it came from, so it won’t behave as expected.

2 Likes

I’m not sure if i need physics for this kind of game, but if you were to use physics and moving with velocity how would you go to moving player one tile / key stroke?

I think for camera following character i need physics anyway, so probably need to write again controlling part…

You just wouldn’t rely on the physics engine to handle collisions with the tilemap, only collisions with other objects. However, I personally wouldn’t mix grid-based movement with physics because collisions would end up misaligning the characters.

A camera can follow any object, no matter if it’s controlled by physics or not. See the examples.

2 Likes