| 23 | }; |
| 24 | |
| 25 | export default class GameEngine extends Component { |
| 26 | constructor(props) { |
| 27 | super(props); |
| 28 | this.state = { |
| 29 | entities: null |
| 30 | }; |
| 31 | this.timer = props.timer || new DefaultTimer(); |
| 32 | this.timer.subscribe(this.updateHandler); |
| 33 | this.touches = []; |
| 34 | this.screen = Dimensions.get("window"); |
| 35 | this.previousTime = null; |
| 36 | this.previousDelta = null; |
| 37 | this.events = []; |
| 38 | this.touchProcessor = props.touchProcessor(this.touches); |
| 39 | this.layout = null; |
| 40 | } |
| 41 | |
| 42 | async componentDidMount() { |
| 43 | let entities = getEntitiesFromProps(this.props); |
| 44 | |
| 45 | if (isPromise(entities)) entities = await entities; |
| 46 | |
| 47 | this.setState( |
| 48 | { |
| 49 | entities: entities || {} |
| 50 | }, |
| 51 | () => { |
| 52 | if (this.props.running) this.start(); |
| 53 | } |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | componentWillUnmount() { |
| 58 | this.stop(); |
| 59 | this.timer.unsubscribe(this.updateHandler); |
| 60 | if (this.touchProcessor.end) this.touchProcessor.end(); |
| 61 | } |
| 62 | |
| 63 | UNSAFE_componentWillReceiveProps(nextProps) { |
| 64 | if (nextProps.running !== this.props.running) { |
| 65 | if (nextProps.running) this.start(); |
| 66 | else this.stop(); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | clear = () => { |
| 71 | this.touches.length = 0; |
| 72 | this.events.length = 0; |
| 73 | this.previousTime = null; |
| 74 | this.previousDelta = null; |
| 75 | }; |
| 76 | |
| 77 | start = () => { |
| 78 | this.clear(); |
| 79 | this.timer.start(); |
| 80 | this.dispatch({ type: "started" }); |
| 81 | }; |
| 82 | |