{"id":13468677,"url":"https://github.com/bberak/react-native-game-engine","last_synced_at":"2025-05-14T09:06:24.795Z","repository":{"id":42681061,"uuid":"94740473","full_name":"bberak/react-native-game-engine","owner":"bberak","description":"A lightweight Game Engine for React Native 🕹⚡🎮","archived":false,"fork":false,"pushed_at":"2024-12-31T04:31:45.000Z","size":527,"stargazers_count":2976,"open_issues_count":19,"forks_count":180,"subscribers_count":63,"default_branch":"master","last_synced_at":"2025-04-11T03:38:10.467Z","etag":null,"topics":["game-2d","game-development","game-engine","react","react-native"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bberak.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2017-06-19T05:41:41.000Z","updated_at":"2025-04-08T05:01:08.000Z","dependencies_parsed_at":"2025-04-11T03:42:03.097Z","dependency_job_id":null,"html_url":"https://github.com/bberak/react-native-game-engine","commit_stats":{"total_commits":176,"total_committers":7,"mean_commits":"25.142857142857142","dds":0.03977272727272729,"last_synced_commit":"01d0827b5d5989cc559dec07d8fdad580bece494"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bberak%2Freact-native-game-engine","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bberak%2Freact-native-game-engine/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bberak%2Freact-native-game-engine/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bberak%2Freact-native-game-engine/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bberak","download_url":"https://codeload.github.com/bberak/react-native-game-engine/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254110374,"owners_count":22016391,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["game-2d","game-development","game-engine","react","react-native"],"created_at":"2024-07-31T15:01:16.578Z","updated_at":"2025-05-14T09:06:24.761Z","avatar_url":"https://github.com/bberak.png","language":"JavaScript","funding_links":[],"categories":["JavaScript","📦 Legacy \u0026 Inactive Projects"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/bberak/react-native-game-engine/master/logo.png\" alt=\"React Native Game Engine\" height=\"120\" /\u003e\n\u003c/p\u003e\n\n# React Native Game Engine \u0026middot; [![npm version](https://badge.fury.io/js/react-native-game-engine.svg)](https://badge.fury.io/js/react-native-game-engine) [![mit license](https://img.shields.io/badge/license-MIT-50CB22.svg)](https://opensource.org/licenses/MIT)\n\nSome components that make it easier to construct dynamic and interactive scenes using React Native.\n\nIf you are looking for the **React (Web)** version of this library, go to [react-game-engine](https://github.com/bberak/react-game-engine).\n\n## Table of Contents\n\n- [Examples](#examples)\n- [Quick Start](#quick-start)\n- [GameEngine Properties](#gameengine-properties)\n- [GameEngine Methods](#gameengine-methods)\n- [FAQ](#faq)\n- [Introduction](#introduction)\n- [The Game Loop](#the-game-loop)\n- [The Game Loop vs React Native](#the-game-loop-vs-react-native)\n- [Using the GameLoop Component](#using-the-gameloop-component)\n  - [Behind the Scenes](#behind-the-scenes)\n  - [Where is the Draw Function?](#where-is-the-draw-function)\n- [Managing Complexity with Component Entity Systems](#managing-complexity-with-component-entity-systems)\n  - [Additional CES Reading Material](#additional-ces-reading-material)\n- [Using the GameEngine Component](#using-the-gameengine-component)\n- [Awesome Packages for Game Development](#awesome-packages-for-game-development)\n- [Get in Touch](#get-in-touch)\n- [License](#license)\n\n## Examples\n\nCheck out [Cannon Ball Sea](https://apps.apple.com/us/app/cannon-ball-sea/id6736433554), an incredibly fun physics-based puzzle game with a vibrant aesthetic.\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://apps.apple.com/us/app/cannon-ball-sea/id6736433554\"\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/bberak/react-native-game-engine-handbook/master/assets/cannon-ball-sea-1.png\" height=\"200\" /\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/bberak/react-native-game-engine-handbook/master/assets/cannon-ball-sea-2.png\" height=\"200\" /\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/bberak/react-native-game-engine-handbook/master/assets/cannon-ball-sea-3.png\" height=\"200\" /\u003e\n    \u003cimg src=\"https://raw.githubusercontent.com/bberak/react-native-game-engine-handbook/master/assets/cannon-ball-sea-4.png\" height=\"200\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\nTake a look at [Studious Bear](https://itunes.apple.com/us/app/studious-bear/id1434377602), a super-polished puzzle game with great visuals and music. One of the first published games to use RNGE.\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://itunes.apple.com/us/app/studious-bear/id1434377602\"\u003e\n    \u003cimg src=\"https://is1-ssl.mzstatic.com/image/thumb/Purple118/v4/6e/90/40/6e9040e2-7a02-d011-c050-85326a76b243/pr_source.png/600x0w.jpg\" height=\"440\" /\u003e\n    \u003cimg src=\"https://is5-ssl.mzstatic.com/image/thumb/Purple118/v4/5c/bb/0d/5cbb0d5c-d678-8488-1a5e-a0bc2867e6c9/pr_source.png/600x0w.jpg\" height=\"440\" /\u003e\n    \u003cimg src=\"https://is2-ssl.mzstatic.com/image/thumb/Purple118/v4/e4/aa/0e/e4aa0ebf-c7fb-7b06-df8c-76c40905450f/pr_source.png/600x0w.jpg\" height=\"440\" /\u003e\n    \u003cimg src=\"https://is5-ssl.mzstatic.com/image/thumb/Purple118/v4/e0/05/40/e005407e-e6ef-339e-c4b7-b2b733cb66db/pr_source.png/600x0w.jpg\" height=\"440\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\nSee the [React Native Game Engine Handbook](https://github.com/bberak/react-native-game-engine-handbook) for a complimentary app, examples and ideas.\n\n## Quick Start\n\nIf you've used **react-native-game-engine** before and understand the core concepts, take a look at [react-native-game-engine-template](https://github.com/bberak/react-native-game-engine-template). It's a sort of game kickstarter project that allows you to prototype ideas quickly and comes preloaded with a bunch of stuff like:\n\n- A 3D renderer\n- Physics\n- Particle system\n- Crude sound API\n- Sprite support with animations\n- Etc\n\nOtherwise, continue reading the quick start guide below.\n\n\u003chr /\u003e\n\nFirstly, install the package to your project:\n\n```npm install --save react-native-game-engine```\n\nThen import the GameEngine component:\n\n```javascript\nimport { GameEngine } from \"react-native-game-engine\"\n```\n\nLet's code a scene that incorporates some multi-touch logic. To start with, let's create some components that can be rendered by React. Create a file called ```renderers.js```:\n\n```javascript\nimport React, { PureComponent } from \"react\";\nimport { StyleSheet, View } from \"react-native\";\n\nconst RADIUS = 20;\n\nclass Finger extends PureComponent {\n  render() {\n    const x = this.props.position[0] - RADIUS / 2;\n    const y = this.props.position[1] - RADIUS / 2;\n    return (\n      \u003cView style={[styles.finger, { left: x, top: y }]} /\u003e\n    );\n  }\n}\n\nconst styles = StyleSheet.create({\n  finger: {\n    borderColor: \"#CCC\",\n    borderWidth: 4,\n    borderRadius: RADIUS * 2,\n    width: RADIUS * 2,\n    height: RADIUS * 2,\n    backgroundColor: \"pink\",\n    position: \"absolute\"\n  }\n});\n\nexport { Finger };\n```\n\nNext, let's code our logic in a file called ```systems.js```:\n\n```javascript\nconst MoveFinger = (entities, { touches }) =\u003e {\n\n  //-- I'm choosing to update the game state (entities) directly for the sake of brevity and simplicity.\n  //-- There's nothing stopping you from treating the game state as immutable and returning a copy..\n  //-- Example: return { ...entities, t.id: { UPDATED COMPONENTS }};\n  //-- That said, it's probably worth considering performance implications in either case.\n\n  touches.filter(t =\u003e t.type === \"move\").forEach(t =\u003e {\n    let finger = entities[t.id];\n    if (finger \u0026\u0026 finger.position) {\n      finger.position = [\n        finger.position[0] + t.delta.pageX,\n        finger.position[1] + t.delta.pageY\n      ];\n    }\n  });\n\n  return entities;\n};\n\nexport { MoveFinger };\n```\n\nFinally let's bring it all together in our ```index.ios.js``` (or ```index.android.js```):\n\n```javascript\nimport React, { PureComponent } from \"react\";\nimport { AppRegistry, StyleSheet, StatusBar } from \"react-native\";\nimport { GameEngine } from \"react-native-game-engine\";\nimport { Finger } from \"./renderers\";\nimport { MoveFinger } from \"./systems\"\n\nexport default class BestGameEver extends PureComponent {\n  constructor() {\n    super();\n  }\n\n  render() {\n    return (\n      \u003cGameEngine\n        style={styles.container}\n        systems={[MoveFinger]}\n        entities={{\n          1: { position: [40,  200], renderer: \u003cFinger /\u003e}, //-- Notice that each entity has a unique id (required)\n          2: { position: [100, 200], renderer: \u003cFinger /\u003e}, //-- and a renderer property (optional). If no renderer\n          3: { position: [160, 200], renderer: \u003cFinger /\u003e}, //-- is supplied with the entity - it won't get displayed.\n          4: { position: [220, 200], renderer: \u003cFinger /\u003e},\n          5: { position: [280, 200], renderer: \u003cFinger /\u003e}\n        }}\u003e\n\n        \u003cStatusBar hidden={true} /\u003e\n\n      \u003c/GameEngine\u003e\n    );\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    backgroundColor: \"#FFF\"\n  }\n});\n\nAppRegistry.registerComponent(\"BestGameEver\", () =\u003e BestGameEver);\n```\n\nBuild and run. Each entity is a **\"finger\"** and is assigned to a particular touch id. The touch ids increase as you place more fingers on the screen. Move your fingers around the screen to move the entities. As an exercise, try add a system that will insert another finger entity into the game state when a **\"start\"** touch event is encountered. What about adding a system that removes the closest entity from the game state when a **\"long-press\"** is encountered?\n\nIf you're curious, our ```GameEngine``` component is a loose implementation of the [Compenent-Entity-System](#managing-complexity-with-component-entity-systems) pattern - we've written up a quick intro [here](#managing-complexity-with-component-entity-systems).\n\n## GameEngine Properties\n\n| Prop | Description | Default |\n|---|---|---|\n|**`systems`**|An array of functions to be called on every tick. |`[]`|\n|**`entities`**|An object containing your game's initial entities. This can also be a Promise that resolves to an object containing your entities. This is useful when you need to asynchronously load a texture or other assets during the creation of your entities or level. |`{} or Promise`|\n|**`renderer`**|A function that receives the entities and needs to render them on every tick. ```(entities, screen, layout) =\u003e { /* DRAW ENTITIES */ }``` |`DefaultRenderer`|\n|**`touchProcessor`**|A function that can be used to override the default touch processing behavior |`DefaultTouchProcessor`|\n|**`timer`**|An object that can be used to override the default timer behavior |`new DefaultTimer()`|\n|**`running`**|A boolean that can be used to control whether the game loop is running or not |`true`|\n|**`onEvent`**|A callback for being notified when events are dispatched |`undefined`|\n|**`style`**|An object containing styles for the root container |`undefined`|\n|**`children`**|React components that will be rendered after the entities |`undefined`|\n\n## GameEngine Methods\n\n| Method | Description | Args |\n|---|---|---|\n|**`stop`**|Stop the game loop |`NA`|\n|**`start`**|Start the game loop. |`NA`|\n|**`swap`**|A method that can be called to update your game with new entities. Can be useful for level switching etc. You can also pass a Promise that resolves to an entities object into this method. |`{} or Promise`|\n|**`dispatch`**|A method that can be called to dispatch events. The event will be received by the systems and any `onEvent` callbacks |`event`|\n\n## FAQ\n\n### Is React Native Game Engine suitable for production quality games?\n\n\u003e This depends on your definition of production quality. You're not going to make a AAA title with RNGE. You could however create some more basic games (doesn't mean they can't be fun games), or even jazz up your existing business applications with some interactive eye candy.\n\n\u003e Simple turn-based games, side-scrollers and platformers with a handful of entites and simple physics would be feasible. Bullet-hell style games with many enemies, particles and effects on the screen at one time will struggle with performance - for these sorts of projects React Native is probably not the right choice of technology at the moment.\n\n\u003e Lastly, for quick prototyping, self-education, and personal projects - React Native (and RNGE) should be suitable tools. For large projects that are commercial in nature, my recommendation would be to take a look at more established platforms like [Godot](https://godotengine.org) and [Unity](https://unity.com) first.\n\n### Do you know of any apps that currently utilize this library?\n\n\u003e [Studious Bear](https://itunes.apple.com/us/app/studious-bear/id1434377602) and [React Native Donkey Kong](https://github.com/bberak/react-native-donkey-kong) both use this library. The [React Native Game Engine Handbook](https://github.com/bberak/react-native-game-engine-handbook) is a complimentary app that showcases some examples and ideas. If you're aware of any others or wouldn't mind a shameless plug here - please reach out.\n\n### How do I manage physics?\n\n\u003e RNGE does not come with an out-of-the-box physics engine. We felt that this would be an area where the game designers should be given greater liberty. There are lots of JS-based physics engines out there, each with their pros and cons. Check out [Matter JS](https://github.com/liabru/matter-js) if you're stuck.\n\n### Do I have a choice of renderers?\n\n\u003e How you render your entities is up to you. You can use the stand React Native components (View, Image) or try [react-native-svg](https://github.com/react-native-community/react-native-svg) or go full exotic with [gl-react-native](https://github.com/gre/gl-react-native-v2).\n\n### RNGE doesn't give me sensor data out of the box - what gives?\n\n\u003e I felt that this would be a nice-to-have and for most use cases it would not be required. Hence, I didn't want to burden RNGE users with any native linking or additional configuration. I was also weary about any unnecessary performance and battery costs. Again, it is easy to integrate into the GameEngine and then RNGE Handbook will have an example using [react-native-sensors](https://github.com/react-native-sensors/react-native-sensors).\n\n### Is this compatible with Android and iOS?\n\n\u003e Yes.\n\n### Won't this kind of be harsh on the battery?\n\n\u003e Well kinda.. But so will any game really! It's a bit of a trade-off, hopefully it's worthwhile!\n\n## Introduction\n\nThis package contains only two components:\n\n- ```GameLoop```\n- ```GameEngine```\n\nBoth are standalone components. The ```GameLoop``` is a subset of the ```GameEngine``` and gives you access to an ```onUpdate``` callback that fires every **16ms** (or roughly 60 fps). On top of this, the ```GameLoop``` will supply a reference to the screen (via ```Dimensions.get(\"window\"))```, touch events for multiple fingers (start, end, press, long-press, move) and time + deltas. The ```GameLoop``` is useful for simple interactive scenes, and pretty much stays out of your way.\n\nThe ```GameEngine``` is more opinionated and is a react-friendly implementation of the [Component-Entity-Systems pattern](#managing-complexity-with-component-entity-systems). It provides the same features out of the box as the ```GameEngine``` but also includes a crude event/signaling pipeline for communication between your game and your other React Native components. You probably want to use the ```GameEngine``` to implement slightly more complex games and interactive scenes.\n\n## The Game Loop\n\nThe game loop is a common pattern in game development and other interactive programs. It loosely consists of two main functions that get called over and over again: ```update``` and ```draw```.\n\nThe ```update``` function is responsible for calculating the next state of your game. It updates all of your game objects, taking into consideration physics, ai, movement, input, health/fire/damage etc. We can consider this the *logic* of your game.\n\nOnce the ```update``` function has done its thing - the ```draw``` function is responsible for taking the current state of the game and rendering it to the screen. Typically, this would include drawing characters, scenery and backgrounds, static or dynamic objects, bad guys, special effects and HUD etc.\n\nIdeally, both functions complete within **16ms**, and we start the next iteration of the loop until some loop-breaking condition is encountered: *pause, quit, game over etc*. This might seem like a lot of processing overhead, but unlike regular applications, games are highly interactive and ever changing. The game loop affords us full control over scenes - even when no user input or external events have fired.\n\n## The Game Loop vs React Native\n\nA typical React Native app will only redraw itself when ```this.setState()``` is called on a component with some new state (for lack of better words). Often times, this is a direct response to user input (button presses, keystrokes, swipes) or other event (WebSocket callbacks, push notifications, etc).\n\nThis works perfectly fine (and is even ideal) for a business-oriented app - but it doesn't give the developer fine grained control to create highly interactive and dynamic scenes.\n\n\u003e Unlike most other software, games keep moving even when the user isn’t providing input. If you sit staring at the screen, the game doesn’t freeze. Animations keep animating. Visual effects dance and sparkle. If you’re unlucky, that monster keeps chomping on your hero.\n\n\u003e This is the first key part of a real game loop: it processes user input, but doesn’t wait for it. The loop always keeps spinning - **[Robert Nystrom](http://gameprogrammingpatterns.com/game-loop.html)**\n\nThat said, React Native and game loops are not mutually exclusive, and we can use ```React Native Game Engine``` to bridge the two paradigms.\n\n## Using the GameLoop Component\n\n**The ```GameLoop``` component is suitable for simple scenes and interactions only. For more complex scenes and games, please take a look at the ```GameEngine``` component and have a quick read through [Managing Complexity with Component Entity Systems](#managing-complexity-with-component-entity-systems)**\n\nFirstly, install the package to your project:\n\n```npm install --save react-native-game-engine```\n\nThen import the GameLoop component:\n\n```javascript\nimport { GameLoop } from \"react-native-game-engine\"\n```\n\nLet's code a basic scene with a single moveable game object. Add this into your ```index.ios.js``` (or ```index.android.js```):\n\n```javascript\nimport React, { PureComponent } from \"react\";\nimport { AppRegistry, StyleSheet, Dimensions, View } from \"react-native\";\nimport { GameLoop } from \"react-native-game-engine\";\n\nconst { width: WIDTH, height: HEIGHT } = Dimensions.get(\"window\");\nconst RADIUS = 25;\n\nexport default class BestGameEver extends PureComponent {\n  constructor() {\n    super();\n    this.state = {\n      x: WIDTH / 2 - RADIUS,\n      y: HEIGHT / 2 - RADIUS\n    };\n  }\n\n  updateHandler = ({ touches, screen, layout, time }) =\u003e {\n    let move = touches.find(x =\u003e x.type === \"move\");\n    if (move) {\n      this.setState({\n        x: this.state.x + move.delta.pageX,\n        y: this.state.y + move.delta.pageY\n      });\n    }\n  };\n\n  render() {\n    return (\n      \u003cGameLoop style={styles.container} onUpdate={this.updateHandler}\u003e\n\n        \u003cView style={[styles.player, { left: this.state.x, top: this.state.y }]} /\u003e\n\n      \u003c/GameLoop\u003e\n    );\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    backgroundColor: \"#FFF\"\n  },\n  player: {\n    position: \"absolute\",\n    backgroundColor: \"pink\",\n    width: RADIUS * 2,\n    height: RADIUS * 2,\n    borderRadius: RADIUS * 2\n  }\n});\n\nAppRegistry.registerComponent(\"BestGameEver\", () =\u003e BestGameEver);\n```\n\n### Behind the Scenes\n\n- The ```GameLoop``` starts a timer using ```requestAnimationFrame(fn)```. Effectively, this is our game loop.\n- Each iteration through the loop, the ```GameLoop``` will call the function passed in via ```props.onUpdate```.\n- Our ```updateHandler``` looks for any ```move``` touches that were made between now and the last time through the loop.\n- If found, we update the position of our lone game object using ```this.setState()```.\n\n### Where is the Draw Function\n\nNice observation! Indeed, there is none. The logic of our scene is processed in the ```updateHandler``` function, and our drawing is handled by our component's out-of-the-box ```render()``` function.\n\nAll we've done here is hookup a timer to a function that fires every **~16ms**, and used ```this.setState()``` to force React Native to diff the changes in our scene and send them across the bridge to the host device. ```React Native Game Engine``` only takes care of the game timing and input processing for us.\n\n## Managing Complexity with Component Entity Systems\n\nTypically, game developers have used OOP to implement complex game objects and scenes. Each game object is instantiated from a class, and polymorphism allows code re-use and behaviors to be extended through inheritance. As class hierarchies grow, it becomes increasingly difficult to create new types of game entities without duplicating code or seriously re-thinking the entire class hierarchy.\n\n```\n               [GameEntity]\n                    |\n                    |\n                [Vehicle]\n               /    |    \\\n              /     |     \\\n             /      |      \\\n            /       |       \\\n   [Terrestrial] [Marine] [Airborne]\n           |        |        |\n           |        |        |\n         [Tank]   [Boat]   [Jet]\n```\n\u003e How do we insert a new terrestrial and marine-based vehicle - say a Hovercraft - into the class hierarchy?\n\nOne way to address these problems is to favor composition over inheritance. With this approach, we break out the attributes and behaviours of our various game entities into decoupled, encapsulated and atomic components. This allows us to be really imaginative with the sorts of game entities we create because we can easily compose them with components from disparate domains and concerns.\n\nComponent entity systems are one way to organize your game entities in a composable manner. To start with, we take the common attributes (data) of our game entities and move them into siloed components. These don't have to be concrete classes, simple hash maps (or equivalent) and scalars will do - but this depends on the data you're storing.\n\n- ***Position:**     { x: 0, y: 0 }*\n- ***Velocity:**     { x: 0, y: 0 }*\n- ***Acceleration:** { x: 0, y: 0 }*\n- ***Mass:**         1.0*\n- ***Health:**       100*\n- ***Physics:**      Body b*\n- ***Controls:**     { jump: 'w', left: 'a', crouch: 's', right: 'd' }*\n\n\u003e Examples of different types of components in a hypothetical programming language.\n\nYour game entities will be reduced to lists/arrays of components and labeled with a unique identifier. An entity's components are by no means static - you're free to update components and even add or remove them on the fly. If our favourite Italian plumber ingests a mushroom, we simple double his velocity. If our character turns into a ghost - we remove his physics component and let him walk through walls.\n\n- ***Player#1:**   [Position, Velocity, Health, Sprite, Physics, Controls]*\n- ***Enemy#1:**    [Position, Velocity, Health, Sprite, Physics, AI]*\n- ***Platform#1:** [Position, Sprite, Physics]*\n- ***Platform#2:** [Position, Sprite, Physics, Velocity] // \u003c-- Moving platform!*\n\n\u003e All entities are assigned a unique id.\n\nSince our entities are simple data holders now, we must move all our game logic into our systems. At its core, a system is a function that processes related groups of components and is called on each iteration of the game loop. The system will extract entities that contain the necessary components it requires to run, update those entities as necessary, and wait for the next cycle. For example, we could code a \"Gravity\" component that calculates the force of gravity and applies it to all entities that have an acceleration AND velocity AND mass component. Entities that do not contain these components will not be affected by gravity.\n\n- ***Gravity:**  (Acceleration, Velocity, Mass) =\u003e { // Update all matching entities // }*\n- ***Render:**   (Sprite, Position) =\u003e { }*\n- ***Movement:** (Position, Velocity, Controls) =\u003e { }*\n- ***Damage:**   (Health) =\u003e { }*\n- ***Bot:**      (Position, Velocity, AI) =\u003e { }*\n\n\u003e The logic in a system is inherently reusable because it can be applied to all entities that meet the system's criteria.\n\nHow exactly you choose to define your components, entities and systems is up to you. You'll probably find that coming up with well-defined components and systems will take some practice - but the general pattern is conducive to refactoring and the long term benefits will outweigh the learning curve.\n\n### Additional CES Reading Material\n\n- [Gamedev.net article](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/understanding-component-entity-systems-r3013/)\n- [Intro to Entity Systems](https://github.com/junkdog/artemis-odb/wiki/Introduction-to-Entity-Systems)\n- [Intro to CES from A-Frame](https://aframe.io/docs/0.7.0/introduction/entity-component-system.html)\n\n## Using the GameEngine Component\n\nThe ```GameEngine``` component is a loose implementation of a [Component-Entity-Systems architecture](#managing-complexity-with-component-entity-systems). It is a plain React component that allows us to pass in a map of entities (and their components) and an array of systems that will process the entities on each frame. In addition, the ```GameEngine``` will provide touch feedback, screen size, layout and some other niceties to help us code our logic.\n\nTo begin with, install the package to your project:\n\n```npm install --save react-native-game-engine```\n\nThen import the GameEngine component:\n\n```javascript\nimport { GameEngine } from \"react-native-game-engine\"\n```\n\nLet's code a scene that incorporates some multi-touch logic. To start with, let's create some components that can be rendered by React. Create a file called ```renderers.js```:\n\n```javascript\nimport React, { PureComponent } from \"react\";\nimport { StyleSheet, View } from \"react-native\";\n\nconst RADIUS = 20;\n\nclass Finger extends PureComponent {\n  render() {\n    const x = this.props.position[0] - RADIUS / 2;\n    const y = this.props.position[1] - RADIUS / 2;\n    return (\n      \u003cView style={[styles.finger, { left: x, top: y }]} /\u003e\n    );\n  }\n}\n\nconst styles = StyleSheet.create({\n  finger: {\n    borderColor: \"#CCC\",\n    borderWidth: 4,\n    borderRadius: RADIUS * 2,\n    width: RADIUS * 2,\n    height: RADIUS * 2,\n    backgroundColor: \"pink\",\n    position: \"absolute\"\n  }\n});\n\nexport { Finger };\n```\n\nNext, let's code our logic in a file called ```systems.js```:\n\n```javascript\nconst MoveFinger = (entities, { touches }) =\u003e {\n\n  //-- I'm choosing to update the game state (entities) directly for the sake of brevity and simplicity.\n  //-- There's nothing stopping you from treating the game state as immutable and returning a copy..\n  //-- Example: return { ...entities, t.id: { UPDATED COMPONENTS }};\n  //-- That said, it's probably worth considering performance implications in either case.\n\n  touches.filter(t =\u003e t.type === \"move\").forEach(t =\u003e {\n    let finger = entities[t.id];\n    if (finger \u0026\u0026 finger.position) {\n      finger.position = [\n        finger.position[0] + t.delta.pageX,\n        finger.position[1] + t.delta.pageY\n      ];\n    }\n  });\n\n  return entities;\n};\n\nexport { MoveFinger };\n```\n\nFinally let's bring it all together in our ```index.ios.js``` (or ```index.android.js```):\n\n```javascript\nimport React, { PureComponent } from \"react\";\nimport { AppRegistry, StyleSheet, StatusBar } from \"react-native\";\nimport { GameEngine } from \"react-native-game-engine\";\nimport { Finger } from \"./renderers\";\nimport { MoveFinger } from \"./systems\"\n\nexport default class BestGameEver extends PureComponent {\n  constructor() {\n    super();\n  }\n\n  render() {\n    return (\n      \u003cGameEngine\n        style={styles.container}\n        systems={[MoveFinger]} //-- We can add as many systems as needed\n        entities={{\n          1: { position: [40,  200], renderer: \u003cFinger /\u003e}, //-- Notice that each entity has a unique id (required)\n          2: { position: [100, 200], renderer: \u003cFinger /\u003e}, //-- and a map of components. Each entity has an optional\n          3: { position: [160, 200], renderer: \u003cFinger /\u003e}, //-- renderer component. If no renderer is supplied with the\n          4: { position: [220, 200], renderer: \u003cFinger /\u003e}, //-- entity - it won't get displayed.\n          5: { position: [280, 200], renderer: \u003cFinger /\u003e}\n        }}\u003e\n\n        \u003cStatusBar hidden={true} /\u003e\n\n      \u003c/GameEngine\u003e\n    );\n  }\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    backgroundColor: \"#FFF\"\n  }\n});\n\nAppRegistry.registerComponent(\"BestGameEver\", () =\u003e BestGameEver);\n```\n\nBuild and run. Each entity is a **\"finger\"** and is assigned to a particular touch id. The touch ids increase as you place more fingers on the screen. Move your fingers around the screen to move the entities. As an exercise, try add a system that will insert another finger entity into the game state when a **\"start\"** touch event is encountered. What about adding a system that removes the closest entity from the game state when a **\"long-press\"** is encountered?\n\n## Awesome Packages for Game Development\n\nThe following is a list of invaluable packages when it comes to coding interactive scenes. Please feel free to nominate others:\n\n- [React Native Animatable](https://github.com/oblador/react-native-animatable)\n- [React Motion](https://github.com/chenglou/react-motion)\n- [Matter JS](https://github.com/liabru/matter-js) (beware has some DOM code)\n- [React Game Kit](https://github.com/FormidableLabs/react-game-kit)\n- [React Native SVG](https://github.com/react-native-community/react-native-svg)\n- [React Native Linear Gradient](https://github.com/react-native-community/react-native-linear-gradient)\n- [React Native Sensors](https://github.com/react-native-sensors/react-native-sensors)\n- [React Native WebGL](https://github.com/react-community/react-native-webgl)\n- [GL React](https://github.com/gre/gl-react)\n\n## License\n\nMIT License\n\nCopyright (c) 2018 Boris Berak\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbberak%2Freact-native-game-engine","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbberak%2Freact-native-game-engine","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbberak%2Freact-native-game-engine/lists"}