Camera following player

Hello, I have a player image which I want the camera to follow. I couldn’t exactly fix this issue which I am facing. If I make the camera follow, my keyboard’s left key is locked and player’s position is wrong. Means, player isn’t moving towards left he moves only up and down.

If I remove camera following, player moves in the expected way (I have set boundaries) but it wouldn’t look like an infinite scroller game.
Please help me in fixing this issue.

Below is my script.
function create ()
{
this.cloud = this.add.tileSprite(0,0,1200,800, ‘cloud’).setScale(2,2.5);
this.player = this.physics.add.image(80, 475, ‘player’).setScale(0.5,0.5).setOrigin(0.5, 1);
this.obstacle = this.physics.add.image(500, 478, ‘obstacle’).setScale(0.25,0.25);
this.cameras.main.setBounds(0, 0, 1200, 800);
this.player.setCollideWorldBounds(true);
this.obstacle.setCollideWorldBounds(true);
this.cloud.setScrollFactor(0.5);
this.cameras.main.startFollow(this.player);

this.physics.add.collider(this.obstacle, this.player, function(obstacle,player){
    obstacle.destroy();
});

}

function update()
{
// this.cloud.body.x -= 8;
this.cloud.tilePositionX -= 8;
this.cursors = this.input.keyboard.createCursorKeys();
if (this.cursors.right.isDown)
{
this.player.body.setVelocityX(500);
}
else if (this.cursors.down.isDown)
{
this.player.body.setVelocityY(300);
}
if ((this.cursors.space.isDown || this.cursors.up.isDown))
{
this.player.body.setVelocityY(-500);
}
else if(this.cursors.left.isDown){
return;
}

}
Thanks

Remove the camera follow (and camera bounds) and use

this.cloud.setScrollFactor(0);

To make camera follow player you have to set scrollX, scrollY in “update”, calculated from player coorinates :

var scrol_x = spr_player.x - game.config.width/2;    
var scrol_y = spr_player.y - game.config.height/2;    

     my_this.cameras.main.scrollX = scrol_x;    ///  scrollX - Х top left point of camera
     my_this.cameras.main.scrollY = scrol_y;    ///  scrollY - Y top left point of camera

Thanks, It worked

1 Like