Making a simple game - Griffith-ICT/1701ICT-Creative-Coding GitHub Wiki
We are going to make a simple game which involves moving a robot around the screen.
Game State
Games generally have something called state. State is all of the data about the game at a single point in time. For example, at the current point time our robot may be at the position (50, 50), but in the next frame it could be at (50, 55).
A game must store its state, generally in global variables, so that we can access them later in the game. The type of things that might make up a game's state:
- The location of objects on the screen
- The current score
- Time remaining (or perhaps when the game started)
- Ammunition left
- Number of lives remaining
For now we are going to have just one object on the screen: the robot. We will need to know the robot's x and y location. Therefore we will have two variables, which will default to the centre of the canvas:
var robotX;
var robotY;
function setup() {
robotX = width / 2;
robotY = height / 2;
}
Drawing the canvas
We need to draw all of our game objects on the canvas. We will just draw the robot at this stage:
function draw() {
image(img, robotX - img.width / 2, robotY - img.height / 2);
}
We subtract half the width and height of the image from the x and y co-ordinates so that the robot image is centred over the x and y co-ordinates. Recall that the image() function parameters indicate the top-left of the image, not the centre.
Move the robot
We are going to move the robot when the arrow keys are pressed. We are going to use the keyPressed() function and move the robot by 5 pixels each time a key is pressed:
function keyPressed() {
if (keyCode === LEFT_ARROW) {
robotX -= 5;
}
if (keyCode === RIGHT_ARROW) {
robotX += 5;
}
if (keyCode === UP_ARROW) {
robotY -= 5;
}
if (keyCode === DOWN_ARROW) {
robotX += 5;
}
}