简体   繁体   中英

Detection with collision in canvas phaser without physics

I have to do a mini video game for a practice. I have coded in Phaser, JavaScript and Java. The canvas is drawn in Phaser.

I need to put collisions in the borders of the world or something when my spaceship touch the canvas limit for my spaceship doesn't go out to the screen.

My teacher forbidden do something with physics like arcade, ninja, or P2.

Its doesn't matter if the solution is in JavaScript or Phaser. Only I need to put limits in the canvas' border.

I have this for drawing the world in Phaser:

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

I have my sprite in the world in the preload :

game.global.myPlayer.image = game.add.sprite(0, 0, 'spacewar', game.global.myPlayer.shipType);

In the create function I have the keyboard control:

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);

In the update function the movement:

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;
}

Not sure how asking for the solution to a school project will help you learn anything..

But anyway, the update() function is called for every frame (60 times per second), so inside that function you can do something like this to prevent the player from moving outside the game area:

// 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;
}

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