npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

expo-phaser

v0.0.1-alpha.0

Published

Build awesome 2D games with Phaser.js and Expo

Downloads

19

Readme

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');
}