Welcome to this week's Monday Snap. We're re-creating the game Cheese Lander using the Snaps game framework. You can find earlier episodes here. Last week we put the bread and the cheese at their start positions. This week we're going to get the cheese moving.
Games work by repeatedly updating the game engine and then re-drawing the display. In a Snaps game we use a C# loop to do this:
At the moment the gameLoop method just repeatedly draws the game page. The DrawGamePage method also pauses the loop so that it runs at the selected frame rate, which for our game is 60Hz. I'm going to add a call of a method to update the cheese position.
The cheese is controlled by the player. The idea is to land it on the bread. This is my first version of the updateCheese method.
int cheeseXSpeed = 2;
int cheeseYSpeed = 2;
cheese.Left += cheeseXSpeed;
cheese.Left -= cheeseXSpeed;
cheese.Top += cheeseYSpeed;
cheese.Top -= cheeseYSpeed;
The SnapsEngine exposes methods that program can use to test the state of the gamepad. You can use the cursor keys on the keypad, a connected Xbox 360/Xbox 1 controller. Alternatively you can use the on-screen touchpad with a mouse, lightpen or finger. If any of the methods return true a speed value is used to update the position of the cheese in that axis. Remember that the Y axis goes down the page. Increasing the Y value of the cheese position will move it down the screen.
This method lets the player move the cheese right off the screen, so perhaps we should fix that.
if (cheese.Left < 0)
cheese.Left = 0;
if (cheese.Right > (SnapsEngine.GameViewportWidth))
cheese.Right = SnapsEngine.GameViewportWidth;
if (cheese.Top < 0)
cheese.Top = 0;
if (cheese.Bottom > SnapsEngine.GameViewportHeight)
cheese.Bottom = SnapsEngine.GameViewportHeight;
These statements "clamp" the cheese movement so that it can't move off the screen. Add them to the updateCheese method after you have updated the cheese position.
You can now steer the cheese around the screen and land it on the bread. Unfortunately this is far too easy. So next week we'll put on our scientists white coats and add some Physics.
And remember, the Monday Snaps are brought to you by Begin to Code With C#, available from all good booksellers.