Camera Move - RPG Tutorial 3

Today I am picking up right where I left off from our last tutorial and showing you how to move your tilemap with your keyboard arrows!

We don’t need to do anything in our preload() function, so we will skip on down to the create() function. Two lines need to be added with this function as shown below:

// set bounds to tilemap size, 0, 800, 800);

// set keyboard input listeners
cursors = game.input.keyboard.createCursorKeys();

The first line is setting our world boundaries. Since our tilemap that we created in tutorial 2 is 800px by 800px, that is what we will set as our last two arguments passed. The first two are the x and y of the starting top left corner of the paint, so we want these to be 0, 0,. Explore changing these numbers up and see how it effects the start position and how far past the painted canvas it will go… (you’ll see the grey background if it’s more than 800px).

The next line is pretty self explanatory, we want the game to know and listen for/accept keyboard events.

That’s it for the create() function, now on to our first interaction with the update() function! This gets called very very frequently, hence the commented out console.log(). We are going to want to pop these lines into this function:

// console.log('call::update()');

// speed of movement
var movementRate = 3;

// only move one direction at a time
if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { -= movementRate;
} else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { += movementRate;
} else if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) { -= movementRate;
} else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) { += movementRate;

Our first line is the movement rate of a single arrow click, controlling the literal movement speed/distance.

Our next if/else statement is handling which direction the camera should go depending on what key was pressed. Notice the built in functions Phaser provides, this makes things very easy to tap into but also very easy to understand what is going on!

That’s it for this tutorial! Check out my next tutorial, Adding a Sprite.

Demo the thing…

Open Demo

Download Source Files

If you would like the source files for this tutorial: Download source files

View Files on Github

Github Folder