Giter Club home page Giter Club logo

expo-phaser's Introduction

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.

expo-phaser's People

Contributors

calebnance avatar dependabot[bot] avatar evanbacon avatar ide avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

expo-phaser's Issues

ExpoPhaser on Android not working

Trying to add ExpoPhaser to my Expo Android app and just making a game object causes the app to error. I am using a Galaxy S8.

undefined is not an object (evaluating window.emitter.emit

Not sure what to make of the error. Seems to build okay on the iOS simulator.

Can provide more details if needed. Thanks for library! Really like the idea!

New Logo

Hello expo.
You have a great app, unfortunately this app does not have a logo yet, may I donate a logo for your app?

It cause the error on expo version 38.0.8

Invariant violation: Imagestore has been removed from react-native. To get base64-ecoded string from a local user either of the following third-party library:* 'expo-file-system': readAsStringAsync(filepath,base64)* react-native-fs :readFile(filepath,base64)

Here are the library I am using right now
"dependencies": {
"expo": "~38.0.8",
"expo-file-system": "~9.0.1",
"expo-gl": "~8.3.1",
"expo-phaser": "^0.0.1-alpha.0",
"expo-status-bar": "^1.0.2",
"react": "~16.11.0",
"react-dom": "~16.11.0",
"react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz",
"react-native-web": "~0.11.7"
}

Here is the app.js code

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import ExpoPhaser from "expo-phaser";
import { GLView } from 'expo-gl';

export default function App() {
return (

<Text style={{ marginTop: 50}}>Open up App.js to start working on your app!

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

);
}

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

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

Please check this issue and let us know

[SUPPORT] TypeError in game.js when setting global.document.readyState

Please let me know if this should be posted in the Expo forums instead of here. When following the basic example in the README I get the following error

TypeError: Cannot assign to read only property 'readyState' of object '#'

Module.game
node_modules/expo-phaser/lib/game.js:12
   9 |   onRender,
  10 | }): Phaser.Game {
  11 |   global.__context = context;
> 12 |   global.document.readyState = 'complete';
  13 |   const game = new Phaser.Game(
  14 |     width || context.drawingBufferWidth,
  15 |     height || context.drawingBufferHeight,

If I comment out the line in question the scene seems to load correctly. Is there something I'm doing wrong in my setup?

Here is an example of my app which is extremely simple.

import React from 'react';
import { GLView } from 'expo-gl';
import ExpoPhaser from "expo-phaser";

export default function App() {
  return (
    <GLView
      style={{ flex: 1 }}
      onContextCreate={context => startGame({ context })}
    />
  );
}

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

  game.state.add("Playable", {
    create: function() {
      game.stage.backgroundColor = "#4488AA";
    }
  });

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

Versions

Node: v12.15.0
Expo: v3.16.1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.