Building Snake with react-native-game-engine

  • A game loop
  • An entity rendering system
  • It handles touch events
  • It has the ability to send and receive custom events to and from the engine
npm install --save react-native-game-engine
  • A set of entities to be rendered at each tick.
  • One or more “systems”. These are essentially instructions to be executed on each tick.

Our Entities

Let’s get to it

  1. Notice we are using a running state variable and we are passing it in to the GameEngine as a prop. It will be very useful to stop the game loop if the user dies.
  2. We keep a reference to the GameEngine in the this.engine instance variable. We will use this to call certain methods on the GameEngine
  3. We are passing in an onEvent event handler to the GameEngine. This method will be executed every time a new event is dispatched using GameEngine.dispatch. Dispatch is the way we can communicate between the main app and the game loop. We will emit different type of events.
  4. Notice these props on our Head entity: nextMove: 10, updateFrequency: 10
    The out of the box game loop is close to 60 frame per sec. We don’t want to update our Head’s position on every tick so we will use nextMove and updateFrequency to slow the update down. More on this later.
  5. I’ve added some on screen controls. Each of them will emit an event with type “move-*” that our Systems will listen to and change the Head’s x and yspeed accordingly.

Rendering

The GameLoop

  • Remember how we passed in nextMove = 10 and updateFrequency = 10 to our Head entity? With each tick we decrement the nextMove by one. Once it hits 0 we are performing some calculations on the environment. This way the game is slowed down to move at every 10 ticks
  • First we are checking if the head did move outside of our playing grid. If so we are dispatching an event with the “game-over” type. Our index.js’ onEvent method will listen to this event and stops the game.
  • If the Head is inside the playing grid we update it’s position by xspeed and yspeed
  • Prepend the food’s position to our Tail’s elements
  • Generate a new random position for our Food so it will pop up at a new location.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Tips for Using TypeScript with styled-components

Install NodeJS on Linux (manually)

Creating a Drag and Drop System in React

What got us excited at React Europe 2018 🇫🇷

Tips To Effectively Master JavaScript

Bounding box in Angular 8

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Tamas Szikszai

Tamas Szikszai

More from Medium

How to: Social Login (Google/Apple) in your Firebase, React Native (Expo) App

Setting Up React-Native with Typescript Environment in Mac OS

Expo CLI vs React Native CLI