keyboard input camera movement (solution)

Hello all, this is a simple fix I came up with, but it might save some people some time searching so I decided to post it here.

First create an empty sprite, set it invisible:
this.cameraFocus = this.physics.add.sprite(0,0,‘cameraFocus’)
this.cameraFocus.visible = false

define cursors:
this.cursors = this.input.keyboard.addKeys(“W,A,S,D”);

Set your camera to follow the sprite:
this.cameras.main.startFollow(cameraFocus,false);

And map keyboard input to movement of the sprite, write this code in the update method:
if (this.cursors.A.isDown) {
this.cameraFocus.setVelocityX(-movementSpeed)
} else if (this.cursors.D.isDown) {
this.cameraFocus.setVelocityX(movementSpeed)
} else {
this.cameraFocus.setVelocityX(0)
}
if (this.cursors.W.isDown) {
this.cameraFocus.setVelocityY(-movementSpeed)
} else if (this.cursors.S.isDown) {
this.cameraFocus.setVelocityY(movementSpeed)
} else {
this.cameraFocus.setVelocityY(0)
}

Anything movement you want the camera to do, you move the sprite. Make sure its gravity and physics body are turned off if they are on. Listen for the scroll event and apply a change to the cameras zoom property for zooming in and out.

1 Like