• Stars
    star
    212
  • Rank 186,122 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Use Phaser.js on mobile with Expo GL

NPM

expo-phaser

Tools for using Phaser-ce to build native 2D games in Expo πŸ‘Ύ

Installation

yarn add expo-phaser

Usage

Import the library into your JavaScript file:

import ExpoPhaser from "expo-phaser";

Functions

ExpoPhaser.game({ context: WebGLRenderingContext, ...extras })

Given a context from an Expo.GLView, return a Phaser.Game that draws into it.

Props

Property Type Description Default Value
context WebGLRenderingContext Required: context that the Phaser.Game will render to null
width number? Optional: height of the Phaser.Game context.drawingBufferWidth
height number? Optional: width of the Phaser.Game context.drawingBufferHeight
title string? Optional: title of the Phaser.Game "expo-phaser-game"
preventLoop boolean? Optional: Prevents the app from calling context.endFrameEXP() every frame false

Returns

Property Type Description
game Phaser.Game The Phaser-ce game used for rendering game logic

Example

const game = ExpoPhaser.game({ context });

What does it do?

Under the hood, ExpoPhaser is maintaining global instances of a few libraries.

window.PIXI = require("phaser-ce/build/custom/pixi");
window.p2 = require("phaser-ce/build/custom/p2");
window.Phaser = require("phaser-ce/build/phaser");

Other libs can be included but are not required. For instance you can import the custom Creature lib the same way. We also override the PIXI.WebGLRenderer.updateTexture to make it compatible with Expo.

Finally when a new instance of Expo.Game is created, we set the document.readyState to 'complete' and save the global instance of context

global.__context = context;
global.document.readyState = "complete";

Then we create a standard render loop and call context.endFrameEXP() to flush the frame queue and render our context through EXGL.

const render = () => {
  requestAnimationFrame(render);
  context.endFrameEXP();
};

Example

It's important to note that you must preload all of your assets before starting the app, as the Phaser.State.preload method cannot be asynchronous. Creating a game in Expo is very simple with ExpoPhaser, we preload our assets, create a view, initialize our game, then add our assets.

We create an Expo.GLView to render our game to.

return (
  <Expo.GLView
    style={{ flex: 1 }}
    onContextCreate={context => startGame({ context })}
  />
);

Then we create our Phaser.Game instance and assign it a playable state. We can then choose to start said state.

function startGame({ context }) {
  const game = ExpoPhaser.game({ context });

  game.state.add("Playable", {
    preload: function() {
      /// This function cannot be async, preload all assets before getting here.
      game.load.image(
        "man",
        Expo.Asset.fromModule(Assets["man.json"]).localUri
      );
    },
    create: function() {},
    update: function() {}
  });

  game.state.start("Playable");
}

Preloading

In React Native all assets must be static resources, because of this we must create a reference to all the assets we may use, then download them and get their local URI. Expo has a convenient way of saving reference. We preload an Expo.Asset then if we create the same instance later we can simple call asset.localUri.

In a standard Phaser app we would load an asset like this:

game.load.image("man", "./assets/man.png");

In expo we would load it like this:

const preloadedExpoAsset = Expo.Asset.fromModule(require('./assets/man.png'))
await preloadedExpoAsset.downloadAsync();

...

game.load.image('man', preloadedExpoAsset.localUri);

All together

This example shows how to load an animated texture atlas and apply arcade physics to it.

import React from "react";
import Expo from "expo";
import ExpoPhaser from "expo-phaser";

const Assets = {
  "man.png": require("./assets/man.png"),
  "man.json": require("./assets/man.json")
};

export default class App extends React.Component {
  state = { loading: true };
  async componentWillMount() {
    const downloads = [];
    for (let key of Object.keys(Assets)) {
      const asset = Expo.Asset.fromModule(Assets[key]);
      downloads.push(asset.downloadAsync());
    }
    await Promise.all(downloads);
    this.setState({ loading: false });
  }
  render() {
    if (this.state.loading) {
      return <Expo.AppLoading />;
    }

    return (
      <Expo.GLView
        style={{ flex: 1 }}
        onContextCreate={context => startGame({ context })}
      />
    );
  }
}

function startGame({ context }) {
  const game = ExpoPhaser.game({ context });

  game.state.add("Playable", {
    preload: function() {
      const atlas = Expo.Asset.fromModule(Assets["man.json"]).localUri;
      const texture = Expo.Asset.fromModule(Assets["man.png"]).localUri;
      game.load.atlasJSONHash("man", texture, atlas);
    },
    create: function() {
      game.stage.backgroundColor = "#4488AA";

      game.physics.startSystem(Phaser.Physics.ARCADE);

      //  Set the world (global) gravity
      game.physics.arcade.gravity.y = 100;

      const man = game.add.sprite(200, 200, "man");
      game.physics.enable([man], Phaser.Physics.ARCADE);

      //  Here we add a new animation called 'run'
      //  We haven't specified any frames because it's using every frame in the texture atlas

      man.animations.add("run");
      man.body.collideWorldBounds = true;
      man.body.bounce.y = 0.8;
      man.body.gravity.y = 200;

      //  And this starts the animation playing by using its key ("run")
      //  15 is the frame rate (15fps)
      //  true means it will loop when it finishes
      man.animations.play("run", 15, true);
    },
    update: function() {}
  });

  game.state.start("Playable");
}

note: When working with .json asset inclusion, be sure to update the app.json file to handle .json appropriately.

"packagerOpts": {
  "assetExts": [
    "json"
  ]
},

Demo

Within this repo is an examples/basic demo.

More Repositories

1

expo

An open-source framework for making universal native apps with React. Expo runs on Android, iOS, and the web.
TypeScript
33,454
star
2

create-react-native-app

Create React Native apps that run on iOS, Android, and web
TypeScript
13,151
star
3

expo-cli

Tools for creating, running, and deploying universal Expo and React Native apps
TypeScript
2,608
star
4

examples

Example projects that demonstrate how to use Expo APIs and integrate Expo with other popular tools
JavaScript
1,567
star
5

react-native-action-sheet

A cross-platform ActionSheet for React Native
TypeScript
1,384
star
6

router

[ARCHIVE]: Expo Router has moved to expo/expo -- The File-based router for universal React Native apps
TypeScript
1,367
star
7

xde

The Expo Development Environment
JavaScript
1,168
star
8

ex-navigation

Route-centric navigation for React Native
JavaScript
1,003
star
9

eas-cli

Fastest way to build, submit, and update iOS and Android apps
TypeScript
800
star
10

react-conf-app

TypeScript
791
star
11

google-fonts

Use any of the 1000+ fonts (and their variants) from fonts.google.com in your Expo app.
JavaScript
788
star
12

expo-github-action

Expo GitHub Action makes it easy to automate EAS builds or updates
TypeScript
782
star
13

fyi

Little bits of information that you may find useful when interacting with Expo tools and service. Append the markdown filename to https://expo.fyi/ to get a quick link to it.
759
star
14

expo-server-sdk-node

Server-side library for working with Expo using Node.js
TypeScript
674
star
15

vector-icons

JavaScript
646
star
16

expo-three

Utilities for using THREE.js on Expo
TypeScript
619
star
17

react-native-read-more-text

JavaScript
572
star
18

ex-navigator

Route-centric navigation built on top of React Native's Navigator
JavaScript
522
star
19

react-native-infinite-scroll-view

An infinitely scrolling view that notifies you as the scroll offset approaches the bottom
JavaScript
520
star
20

awesome-expo

Useful resources for creating apps with Exponent
468
star
21

exp

JavaScript
465
star
22

react-native-invertible-scroll-view

An invertible ScrollView for React Native
JavaScript
460
star
23

config-plugins

Out-of-tree Expo config plugins for packages that haven't adopted the config plugin system yet.
TypeScript
457
star
24

orbit

Accelerate your development workflow with one-click build launches and simulator management from your macOS menu bar
TypeScript
436
star
25

vscode-expo

Expo Tools keep you productive with debugging, IntelliSense, and prebuild previews
TypeScript
425
star
26

turtle

Standalone app builder service
TypeScript
384
star
27

snack

Expo Snack lets you run Expo in the browser.
TypeScript
366
star
28

react-native-appearance

Access operating system appearance information (currently only light/dark mode) on iOS, Android, and web
Java
337
star
29

expo-pixi

Tools for using pixi.js in Expo
JavaScript
300
star
30

custom-expo-updates-server

A simplified demonstration of expo-updates protocol use.
TypeScript
295
star
31

use-unmount-signal

A React Hook to cancel promises when a component is unmounted
TypeScript
292
star
32

web-examples

Examples of using Expo in the browser.
JavaScript
272
star
33

image-upload-example

Demonstration of how to upload images from the ImagePicker, using a node backend to upload to S3
JavaScript
228
star
34

snack-web

TypeScript
215
star
35

sentry-expo

TypeScript
201
star
36

fluxpybird

some ideas involving games and Redux
JavaScript
179
star
37

stripe-expo

Use the Stripe HTTP API in Expo without the DOM, node, or native deps
JavaScript
160
star
38

react-native-responsive-image

A responsive Image component that chooses the best-resolution image for the current screen
JavaScript
160
star
39

react-native-loading-container

A container component that takes care of loading/catching timeouts/retrying
JavaScript
156
star
40

camerja

JavaScript
156
star
41

dev-plugins

Out-of-tree Expo devtools plugins for packages that haven't adopted the Expo devtools plugin system yet.
TypeScript
152
star
42

playlist-example

JavaScript
151
star
43

entity

Entity is a privacy-aware data layer for defining, caching, and authorizing access to application data models.
TypeScript
140
star
44

match-media

Universal polyfill for match media API using Expo APIs on mobile
TypeScript
136
star
45

react-native-fade-in-image

JavaScript
118
star
46

atlas

Visualize React Native bundles to understand and optimize your app.
TypeScript
114
star
47

eslint-config-universe

Moved to https://github.com/expo/expo/tree/master/packages/eslint-config-universe
JavaScript
110
star
48

expo-2d-context

A pure-js implementation of the W3C's Canvas-2D Context API that can be run on either Expo Graphics or WebGL
HTML
110
star
49

audio-recording-example

Audio Recording Example
TypeScript
109
star
50

redux-effex

Spin off async functions to perform side effects
JavaScript
108
star
51

auth0-example

This example has moved
JavaScript
108
star
52

results

An efficient, standards-compliant library for representing results of successful or failed operations
TypeScript
102
star
53

firebase-storage-upload-example

This example has moved
JavaScript
98
star
54

sqlite-example

This example has moved
JavaScript
97
star
55

react-native-scrollable-mixin

A standard interface for your scrollable React Native components, making it easier to compose components.
JavaScript
94
star
56

expo-processing

Utilities for using Processing.js on Expo
JavaScript
93
star
57

videoplayer

Customizable controls for Expo video
JavaScript
83
star
58

snack-sdk

Snack SDK
JavaScript
83
star
59

react-apple-easing

Apple's default Core Animation easing functions for React
JavaScript
83
star
60

turtle-cli-example

Turtle CLI usage example (CircleCI & Travis CI)
Shell
81
star
61

eas-build

TypeScript
77
star
62

dire-dire-ducks

Flood your room with water and rubber duckies!
JavaScript
77
star
63

expo-preview-action

With this preview action, you can test changes made in pull requests via Expo Go or custom development client (created with expo-dev-client) just by scanning QR code.
JavaScript
75
star
64

status-bar-height

Listen to status bar changes during incoming calls and other multi-tasking events
JavaScript
73
star
65

expo-three-ar

Utilities for using Expo AR with THREE.js
TypeScript
72
star
66

react-native-image-gallery

JavaScript
71
star
67

pomodoroexp

https://expo.io/@community/pomodoro
JavaScript
70
star
68

react-native-refreshable-scroll-view

A ScrollView that supports pull-to-refresh. You can customize it with the RefreshIndicator and type of ScrollView (ex: ListView) of your choice.
JavaScript
61
star
69

spawn-async

A Promise-based interface into processes created by child_process.spawn
TypeScript
59
star
70

react-native-for-curious-people

Available through the Exponent iPhone or Android app:
JavaScript
59
star
71

UpdatesAPIDemo

Demo app showing the useUpdates() API
TypeScript
55
star
72

browser-polyfill

Browser polyfill for making React Native compatible with web libs like pixi.js, three.js, phaser.js
JavaScript
52
star
73

xdl

The Expo Development Library
TypeScript
47
star
74

harvard-cs50-app

Harvard's mobile application for CS50.
JavaScript
46
star
75

styleguide

Foundational styles for Expo interfaces.
TypeScript
45
star
76

hello-graphql

JavaScript
44
star
77

expo-graphics

Tools to help simplify working with three, pixi, phaser, ect...
JavaScript
44
star
78

detox-expo-helpers

JavaScript
43
star
79

expo-asset-utils

Utilities for parsing files references, and Expo Assets.
TypeScript
42
star
80

hackathon-examples

40
star
81

with-detox-tests

This template is no longer maintained! See https://github.com/yaron1m/expo-detox-typescript-example instead
JavaScript
39
star
82

react-native-scrollable-decorator

A standard interface for your scrollable React Native components, making it easier to compose components.
JavaScript
38
star
83

react-native-url-handler

Navigate to external URLs, handle in-app URLs, and access system URLs
Objective-C
36
star
84

rnplay

THIS REPOSITORY IS QUITE OLD AND NOT MAINTAINED! React Native Playground has been replaced by https://snack.expo.io. Look at this repository like you might look at tools in a museum, and don't touch it or actually use it
JavaScript
36
star
85

expo-twitter-login-example

This example has moved
JavaScript
34
star
86

react-native-image-picker-android

A camera and gallery image picker native module for Android, giving a subset of the API of https://github.com/marcshilling/react-native-image-picker
Java
34
star
87

eas-tests-example

Demo of running E2E tests on EAS Build
Java
33
star
88

react-loading-indicator

A loading indicator written purely in React that uses SVG and no images.
JavaScript
32
star
89

socket-io-example

This example has moved
29
star
90

expo-electron-adapter

This package wraps `electron-webpack` and adds support for Expo web and other universal React packages.
TypeScript
28
star
91

koa-graphiql

Koa middleware to display GraphiQL, the interactive GraphQL UI
JavaScript
27
star
92

video-background-example

This example has moved
JavaScript
27
star
93

gl-test

Examples and tests for OpenGL rendering in Expo.
JavaScript
26
star
94

three-ar-test

Using Expo's AR functionality with THREE.js
JavaScript
25
star
95

BrightSky

Learn how to use Expo with this simple weather app!
TypeScript
24
star
96

expo-postpublish-slack-notify

JavaScript
24
star
97

breakout

why not?
JavaScript
24
star
98

hyperinstall

Runs "yarn" and "npm install" in several directories with extreme speed when possible
JavaScript
23
star
99

electron-cookies

Provides document.cookie support for Electron
JavaScript
22
star
100

pound-random

Expo Blue - a discussion app for small groups
JavaScript
22
star