The GameEngine component follows a Component-Entity-System architecture.
- Entities: A map of objects where each key is a unique ID. Each entity contains a set of components (data) and an optional
renderer (a React component). - Systems: Functions that process entities on every frame. A system receives
entities and a second argument containing metadata like touches. Systems should return the updated entities object. - Renderers: React components that receive entity data via
props to draw the entity on screen.
Example Implementation
- Define a Renderer (
renderers.js):
import React, { PureComponent } from "react";
import { StyleSheet, View } from "react-native";
const RADIUS = 20;
class Finger extends PureComponent {
render() {
const x = this.props.position[0] - RADIUS / 2;
const y = this.props.position[1] - RADIUS / 2;
return (
<View style={[styles.finger, { left: x, top: y }]} />
);
}
}
const styles = StyleSheet.create({
finger: {
borderColor: "#CCC",
borderWidth: 4,
borderRadius: RADIUS * 2,
width: RADIUS * 2,
height: RADIUS * 2,
backgroundColor: "pink",
position: "absolute"
}
});
export { Finger };
- Define a System (
systems.js):
const MoveFinger = (entities, { touches }) => {
touches.filter(t => t.type === "move").forEach(t => {
let finger = entities[t.id];
if (finger && finger.position) {
finger.position = [
finger.position[0] + t.delta.pageX,
finger.position[1] + t.delta.pageY
];
}
});
return entities;
};
export { MoveFinger };
- Initialize the GameEngine (
index.js):
import React, { PureComponent } from "react";
import { AppRegistry, StyleSheet, StatusBar } from "react-native";
import { GameEngine } from "react-native-game-engine";
import { Finger } from "./renderers";
import { MoveFinger } from "./systems"
export default class BestGameEver extends PureComponent {
render() {
return (
<GameEngine
style={styles.container}
systems={[MoveFinger]}
entities={{
1: { position: [40, 200], renderer: <Finger />},
2: { position: [100, 200], renderer: <Finger />},
3: { position: [160, 200], renderer: <Finger />},
4: { position: [220, 200], renderer: <Finger />},
5: { position: [280, 200], renderer: <Finger />}
}}>
<StatusBar hidden={true} />
</GameEngine>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#FFF"
}
});
AppRegistry.registerComponent("BestGameEver", () => BestGameEver);
import { GameEngine } from "react-native-game-engine"