Phaser 3 - enabling bounds with key movement

Hi everyone,
Phaser 3 newbie here. I have created the following code. I aim to ctreate a collision with the bounds and stop. Up down key movement. It works. how to use setbounds methods here?

thanks in advance

shriram

let gameScene = new Phaser.Scene(‘Game’);

let config = {

physics: {
default: ‘arcade’,
arcade: {
width: 300,
height: 300,
gravity: {
x: 0,
y: 0,
},
checkCollision: {
up: true,
down: true,
left: true,
right: true
},

}
},

type: Phaser.AUTO,
width: 500, // game width
height: 400, // game height
scene: gameScene
};
let game = new Phaser.Game(config);
gameScene.init = function() {
this.playerSpeed = 1.5;
};

gameScene.preload = function() {
this.load.image(‘background’, ‘sky.png’);
this.load.image(‘player’, ‘boy.png’);
};

gameScene.create = function() {

let bg = this.add.image(0, 0, ‘background’);
this.player = this.add.sprite(70, this.sys.game.config.height/3, ‘player’);
this.player.setScale(0.5);
bg.setOrigin(0,0);
cursors = this.input.keyboard.createCursorKeys();

gameScene.physics.world.setBounds(0, 0, 200, 200);
this.player.setCollideWorldBounds(true);
};

gameScene.update = function() {

console.log(Math.round(this.player.y), this.player.x);
if (cursors.left.isDown)
{
if (this.player.x !=17)
{
this.player.x -=1;
}

} else if (cursors.right.isDown)

{
if (this.player.x !=445)
{
this.player.x +=1;
}

} else if (cursors.up.isDown)
{

if (Math.round(this.player.y) !=37)
{
this.player.y-= 1;
}

} else if (cursors.down.isDown)
{
if (Math.round(this.player.y) !=400)
{
this.player.y+= 1;
}

}

};

Hi,
Collisions only works if you use this.player.body.setVelocityX(100), not with this.player.x +=1
Change your arcade config to this, so you can see bodies used for collisions
Change this.player.setCollideWorldBounds(true); to this.player.body.setCollideWorldBounds(true);

physics: {
    default: ‘arcade’,
    arcade: {
        width: 300,
        height: 300,
        gravity: {
            x: 0,
            y: 0,
        },
        debug: true,
        debugShowBody: true,
        debugShowStaticBody: true,
    }
}

And look at this example:

1 Like

Thanks for the kind reply. I was try to see if i was a method to detect automatically if my player went out of bound. I understand now that i was on the right track to detect through code itself. Thanks