over 3 years ago

## Part 2: Moving Square

Last time we had a simple example - our spinning square - but now we want to go one more step and move it with our keyboard. Before we do that though, we should reorganize our code a little.

First, let's create a struct containing the information of our game:

Now let's create an implementation for it. We're going to move our game and rendering logic into an on_update function and an on_draw function, with some modifications:

We have also added a function to easily create instances of Game, essentially a constructor.

The event loop should now look like this:

One new thing you will notice is Event::Render. This is an event that piston uses to tell us it is time to draw a new frame; it also allows for better decoupling of the render loop from the event loop, such that we don't bog down keyboard input with rendering. It also gives us some more values to work with, such as the current window width and height - which we have used in the modified on_draw code above. We also now capture the Event::Update(UpdateArgs) member, rather than only the delta time; this is to streamline our event function calls.

### The moving the square part

Capturing input is similar to other events in piston:

Before we write on_input, we need some boolean values so we can do movement based on dt; we'll also add some variables for the x and y of our square:

Of course, in Game::new() we have to add default values:

Time to write on_input:

As you can see, we take the Input event argument and match it through one of the possible events - two of which, the ones we use, being Input::Press and Input:Release, representing a button press or release, respectively. We set our *_d variables accordingly.

The last two things we need to do is add movement logic to the update function:

And change the rendering of the square accordingly:

You can find the source code for this part here

Next time we'll load and display a tank sprite instead of a square. For that purpose, we will also start keeping object information in a separate struct, and its code in a separate file.