简体   繁体   中英

Add image on clicked place Phaser3

I want to create a game like Tic-tac toy, but can't set the correct position for the image (inside x() & y() function). Clicking on a special platform(square) want to place x or y inside that platform. In my case, it creates inside the first platform always.

export default class A extends Phaser.Scene {
  constructor () {
    super(SCENE_GAME)
    this.counter = 0
    const gameOptions = {
      tileSize: 200,
    }
    const gameConfig = {
      width: gameOptions.tileSize * 3,
      height: gameOptions.tileSize * 3,
    }
  }

  create = () => {
    this.platformArray = []
    this.platformGroup = this.add.group()
    for (let i = 0; i < 3; i++) {
      this.platformArray[i] = []
      for (let j = 0; j < 3; j++) {
        this.platform = this.add.sprite(j * gameOptions.tileSize + gameOptions.tileSize / 2, i * gameOptions.tileSize + gameOptions.tileSize / 2, 'platform').setInteractive()
        this.platform.on('pointerdown', this.clickCounter, this)
      }
    }
  }

  clickCounter () {
    this.counter++
    if (this.counter % 2 === 1) {
      this.x()
    } else {
      this.y()
    }
  }

  x () {
    this.add.sprite(gameOptions.tileSize / 2, gameOptions.tileSize / 2, 'x')
  }

  y () {
    this.add.sprite(gameOptions.tileSize / 2, gameOptions.tileSize / 2, 'y')
  }

The reason that they're showing up in the same place is because you're using the tileSize only for the positioning.

So if tileSize were 16, x() would always add a sprite at position 8, 8.

In your for loop you have this:

this.platform = this.add.sprite(
    j * gameOptions.tileSize + gameOptions.tileSize / 2,
    i * gameOptions.tileSize + gameOptions.tileSize / 2, 'platform')
 .setInteractive()

You can see that you're taking the tileSize and multiplying by the grid position.

I would recommend changing your x and y functions to accept either a number or a Pointer, which should be already be accessible in clickCounter() if you add the argument (adding a console.log(arguments); in clickCounter() should log out the arguments available).

Based upon the pointer's position you can then do the math to determine what tile was clicked on.

Another alternative would be to add custom properties to each tile sprite, say a row and column , set to the appropriate i / j value. The clicked on sprite should then be accessible in clickCounter too as one of the arguments, and then you can just pull the custom properties.

If you're using TypeScript, you'll want to create a custom object that extends Sprite.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM