How to find tile position to move player to?

Hi there.

I’m currently working on movement. I want to be able to click on a tile and have the player move to it. I thought I’d try to read the position of the tile itself, after a mouse press on a tile.

this.getTile = scene.map.getTileAtWorldXY(pointer.worldXY, pointer.worldXY)

I’ve been using this variable to retrieve the tile based on where I click. Afterwards I used:

scene.physics.moveTo(scene.players.getChildren()[0], this.worldXY.x, this.worldXY.y, 90)

The this.worldXY is a variable that holds the tile sprite in its world position.

this.worldXY = scene.map.tileToWorldXY(this.tile.x, this.tile.y);

I also have the camera following the camera, and set to zoom. Adds a layer to the already difficult task I’ve put ahead of me. I believe it may have something to do with the scroll factor. I’m not sure.

Any suggestions or help would be much appreciated.

What’s not working?

    this.input.on("pointerdown", (pointer)=> {
      let d = map.getTileAtWorldXY(pointer.worldX, pointer.worldY, this.cameras, layer1)
      console.log(d)
    })

I’m trying to get the tile after clicking on it so I can read the world position. It returns null in most of my attempts. I also placed in the boolean for nonNull but that didn’t work either. I’m having another go at this.

Oh I got that part working.

    this.input.on("pointerdown", (pointer)=> {
      let d = map.getTileAtWorldXY(pointer.worldX, pointer.worldY, true)
    })

I’ve written it out in a state machine: I’m giving the pixelX and Y to the moveTo function.

export class PlayerIdleState extends State {
    enter(scene) {
        scene.input.on("pointerdown", (pointer) => {
            tile = scene.map.getTileAtWorldXY(pointer.worldX, pointer.worldY, true)
            this.stateMachine.transition("move", tile)
        })
    }
    execute(scene) {
    }
}

export class PlayerMoveState extends State {
    enter(scene, tile) {
        this.tile = tile
        console.log(tile)
    }
    execute(scene,tile) {
        scene.physics.moveTo(scene.players.getChildren()[0], this.tile.pixelX, this.tile.pixelY, 90)
    }
}

I guess that works. My other issue now is how to make the player stop once it reaches its destination.

1 Like

You can check distance like physics/arcade/move-and-stop-at-position.

90px/s is 1.5px per default-size physics step.

1 Like