[英]Add image on clicked place Phaser3
我想創建一個類似Tic-tac玩具的游戲,但無法為圖像設置正確的位置(在x()
和y()
函數內部)。 單擊特殊的平台(正方形)要在該平台內放置x或y。 就我而言,它總是在第一個平台內創建。
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')
}
它們出現在同一位置的原因是因為您僅將tileSize
用於定位。
因此,如果tileSize
為16, x()
將始終在位置8、8處添加一個sprite。
在您的for
循環中,您有以下內容:
this.platform = this.add.sprite(
j * gameOptions.tileSize + gameOptions.tileSize / 2,
i * gameOptions.tileSize + gameOptions.tileSize / 2, 'platform')
.setInteractive()
您會看到您正在使用tileSize
並乘以網格位置。
我建議您將x
和y
函數更改為接受數字或指針,如果您添加參數(添加console.log(arguments);
在clickCounter()
應該注銷clickCounter()
,則應該已經可以在clickCounter()
訪問它了可用的參數)。
然后,根據指針的位置,可以進行數學運算以確定單擊的圖塊。
另一種替代方法是向每個tile精靈添加自定義屬性,例如將row
和column
設置為適當的i
/ j
值。 然后,點擊的子畫面也應該作為參數之一在clickCounter
可訪問,然后您就可以提取自定義屬性。
如果您使用的是TypeScript,則需要創建一個擴展Sprite的自定義對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.