0
votes

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;
}
1
Please specify what code you're having a problem with by editing in the problem code to your question and explaining the specific issue. How to Ask might have useful tips for you.Matt Ellen
Phaser or not, you need to keep track of the player location (x,y) and the width and height of your canvas. You then just check if the x (horizontal) and y (vertical) player position are within the boundaries of your canvas and refuse a movement that puts the player outsidePhilMaGeo

1 Answers

1
votes

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