在没有物理的 canvas 移相器中进行碰撞检测

Detection with collision in canvas phaser without physics

我必须做一个迷你视频游戏来练习。我在 Phaser、JavaScript 和 Java 中编码。 canvas 在 Phaser 中绘制。

当我的宇宙飞船触及 canvas 限制时,我需要在世界边界或其他地方放置碰撞,因为我的宇宙飞船不会出现在屏幕上。

我的老师禁止做街机、忍者或 P2 等物理方面的事情。

解决方案是在 JavaScript 还是 Phaser 中并不重要。只有我需要在 canvas' 边界中设置限制。

我有这个用于在 Phaser 中绘制世界:

game = new Phaser.Game(1024, 600, Phaser.AUTO, 'gameDiv'

我在 preload:

世界中有我的精灵
game.global.myPlayer.image = game.add.sprite(0, 0, 'spacewar', game.global.myPlayer.shipType);

在创建函数中我有键盘控制:

this.wKey = game.input.keyboard.addKey(Phaser.Keyboard.UP);
this.sKey = game.input.keyboard.addKey(Phaser.Keyboard.DOWN);
this.aKey = game.input.keyboard.addKey(Phaser.Keyboard.LEFT);
this.dKey = game.input.keyboard.addKey(Phaser.Keyboard.RIGHT);
this.spaceKey = game.input.keyboard.addKey(Phaser.Keyboard.CONTROL);
this.shiftKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);

更新函数中的动作:

if (this.wKey.isDown)
    msg.movement.thrust = true;
if (this.sKey.isDown)
    msg.movement.brake = true;
if (this.aKey.isDown)
    msg.movement.rotLeft = true;
if (this.dKey.isDown)
    msg.movement.rotRight = true;
if (this.spaceKey.isDown) {
    msg.bullet = this.fireBullet()
}
if (this.shiftKey.isDown) {
    msg.push = true;
}

不确定寻求学校项目的解决方案将如何帮助您学习任何东西..

但是无论如何,update() 函数每帧都会被调用一次(每秒 60 次),所以在该函数中你可以做这样的事情来防止玩家移动到游戏区域之外:

// cannot move outside game area, left and right
if (game.global.myPlayer.image.x < 0) {
    game.global.myPlayer.image.x = 0;
}
if (game.global.myPlayer.image.x > game.world.width) {
    game.global.myPlayer.image.x = game.world.width;
}

// cannot move outside game area, top and bottom
if (game.global.myPlayer.image.y < 0) {
    game.global.myPlayer.image.y = 0;
}
if (game.global.myPlayer.image.y > game.world.height) {
    game.global.myPlayer.image.y = game.world.height;
}