当前版本一次只能消除一处!
若有不足,欢迎指正!
let’s go!
需求:
- 图标成矩形随机排列
- 可以拖动一行或一列
- 3个或以上个相同图案连在一起时会被消除
0. 先把 Phaser
的主要代码搭起来
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Match</title>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="game"></div>
<script src="/public/js/phaser.min.js"></script>
<script>
let game
let gameOptions = {
iconW: 100, // 图标宽度
iconH: 100, // 图标高度
rows: 10, // 行数
columns: 7, // 列数
iconNum: 6, // 图标数
gameArea: {
// 游戏区域
x: 25,
y: 300
},
movingX: 'x',
movingY: 'y',
}
let gameAreaW = gameOptions.iconW * gameOptions.columns
let gameAreaH = gameOptions.iconH * gameOptions.rows
class PlayGame extends Phaser.Scene {
constructor() {
super('PlayGame')
}
preload() {
this.load.spritesheet('sprite', 'sprite.png', {
frameWidth: gameOptions.iconW,
frameHeight: gameOptions.iconH
})
}
create() {
}
}
let gameConfig = {
type: Phaser.AUTO,
scale: {
mode: Phaser.Scale.WIDTH_CONTROLS_HEIGHT,
autoCenter: Phaser.Scale.CENTER_BOTH,
parent: 'game',
width: 750,
height: 1464
},
scene: PlayGame
}
game = new Phaser.Game(gameConfig)
</script>
</body>
</html>
1. 设置游戏区域容器
class PlayGame extends Phaser.Scene {
create() {
this.itemContainer = this.add.container(gameOptions.gameArea.x, gameOptions.gameArea.y)
let mask = this.make.graphics()
mask.fillStyle(0x00ffff, 1);
mask.fillRect(gameOptions.gameArea.x, gameOptions.gameArea.y, gameOptions.iconW * gameOptions.columns, gameOptions.iconH * gameOptions.rows)
this.itemContainer.setMask(new Phaser.Display.Masks.GeometryMask(this, mask))
this.itemArr = [] // 用来存放所有的小球
}
}
2. 放置小球
class PlayGame extends Phaser.Scene {
create() {
this.putSpirte()
}
putSpirte() {
for (let i = 0; i < gameOptions.columns; i++) {
this.itemArr[i] = []
for (let j = 0; j < gameOptions.rows; j++) {
let iconX = gameOptions.iconW * i
let iconY = gameOptions.iconH * j
let type = Phaser.Math.Between(0, gameOptions.iconNum - 1)
let icon = this.add.sprite(iconX, iconY, 'sprite', type)
icon.setOrigin(0, 0)
icon.rows = j
icon.columns = i
icon.type = type
this.itemArr[i][j] = icon
this.itemContainer.add(icon)
}
}
}
}
3. 拖动小球
3.1 检测触碰区域获取触碰位置
class PlayGame extends Phaser.Scene {
checkArea(pointer) {
let gameArea = new Phaser.Geom.Rectangle(gameOptions.gameArea.x, gameOptions.gameArea.y, gameOptions.columns * gameOptions.iconW, gameOptions.rows * gameOptions.iconH)
return Phaser.Geom.Rectangle.Contains(gameArea, pointer.x, pointer.y)
}
getPos(pointer) {
let col = (pointer.downX - gameOptions.gameArea.x) / gameOptions.iconW
let row = (pointer.downY - gameOptions.gameArea.y) / gameOptions.iconH
this.curRow = Math.floor(row)
this.curCol = Math.floor(col)
}
}
3.2 监听拖动
class PlayGame extends Phaser.Scene {
create() {
this.input.on('pointerdown', this.startHandler, this)
this.input.on('pointermove', this.moveHandler, this)
this.input.on('pointerup'<