Snake Game With Rust, JavaScript, and WebAssembly | Part 5

This is part of the course “Snake Game With Rust, JavaScript, and WebAssembly”.

GitHub Repository and Deployed Game

In this part, we will start the game loop and make the snake move. Changes that we will introduce in this part reflected in this commit.

It is time to add the method that will update the game state. For now, it will only receive milliseconds from the last update. We will handle snake direction change in the next part.

src/lib.rs

We will need two methods to move the snake, so let’s add them first.

src/lib.rs

By using the normalize method, we can convert a vector to a unit vector with the length of one.

Now we are ready to write logic that will change positions of snake edges.

src/lib.rs

We start by calculating the distance the snake was supposed to crawl. Then we update the tail by going over each edge, except the last one(head), and shifting it. Because we don’t handle direction change in this part, the logic to update head position is pretty simple, we add to the old position direction scaled by the distance.

Let’s compile the Rust and go to the JavaScript side.

Let’s update GameManager with the game loop.

www/src/game-manager.js

We are calling the process method to update the game state and render everything 60 times per second.

snake is moving

In the next part, we will handle keypresses and update the snake direction. Stay tuned!

Reach the next level of focus and productivity with increaser.org.

Increaser

Software engineer, creator of increaser.org. More at geekrodion.com