Giter Club home page Giter Club logo

proyecto26 / ion-phaser Goto Github PK

View Code? Open in Web Editor NEW
248.0 8.0 39.0 1.17 MB

A web component to use Phaser Framework with Angular, React, Vue, etc 🎮

Home Page: https://market.ionicframework.com/plugins/ionphaser

License: MIT License

HTML 12.17% CSS 8.34% JavaScript 12.79% TypeScript 60.08% Vue 6.63%
phaser phaserjs phaser3 phaser-framework stenciljs stenciljs-components stencil-components stencil-js custom-elements custom-components react react-component web-component web-components angular vue vuejs custom-component ionic ionic-framework

ion-phaser's Introduction

Built With Stencil Maintenance NPM version Downloads TotalDownloads Twitter Follow

IonPhaser

Web Component built with Stencil.js to integrate Phaser with any other framework.

IonPhaser

Inspired by the old IonPhaser directive

Demo

Do you want to see this web component in action? Visit https://codepen.io/jdnichollsc/full/oRrwKM yay! 🎉

IonPhaser CE

Looking for Phaser Framework CE (Community Edition)? Check here!

Usage

Simply add this tag wherever you want in your project:

<ion-phaser [game]="game"></ion-phaser>

Getting Started

Packages

Project Package Version Links
Core @ion-phaser/core version README.md
React @ion-phaser/react version README.md

Script tag

  • Put a script tag similar to this <script src='https://cdn.jsdelivr.net/npm/@ion-phaser/[email protected]/dist/ionphaser/ionphaser.esm.js'></script> in the head of your index.html
  • Then you can use the element anywhere in your template, JSX, html etc

Node Modules

  • Run npm install @ion-phaser/core --save
  • Put a script tag similar to this <script src='node_modules/@ion-phaser/core/dist/ionphaser/ionphaser.esm.js'></script> in the head of your index.html
  • Then you can use the element anywhere in your template, JSX, html etc

In a stencil-starter app

  • Run npm install @ion-phaser/core --save
  • Add an import to the npm packages import @ion-phaser/core;
  • Then you can use the element anywhere in your template, JSX, html etc

Framework integrations

Angular

Using ion-phaser component within an Angular project:

Including the Custom Elements Schema

Including the CUSTOM_ELEMENTS_SCHEMA in the module allows the use of Web Components in the HTML files. Here is an example of adding it to AppModule:

import { BrowserModule } from '@angular/platform-browser';
import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {}

The CUSTOM_ELEMENTS_SCHEMA needs to be included in any module that uses IonPhaser.

Calling defineCustomElements

IonPhaser component includes a function used to load itself in the application window object. That function is called defineCustomElements() and needs to be executed once during the bootstrapping of your application. One convenient place to add it is in the main.ts file as follows:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { defineCustomElements as defineIonPhaser } from '@ion-phaser/core/loader';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));
defineIonPhaser(window);

Using IonPhaser in an Angular component

<ion-phaser
  [game]="game"
  [initialize]="initialize"
></ion-phaser>
public game = {
  width?: integer | string;
  height?: integer | string;
  zoom?: number;
  resolution?: number;
  type?: number;
  parent: HTMLElement | string;
  canvas?: HTMLCanvasElement;
  canvasStyle?: string;
  context?: CanvasRenderingContext2D;
  scene?: object;
  seed?: string[];
  title?: string;
  url?: string;
  version?: string;
  autoFocus?: boolean;
  input?: boolean | InputConfig;
  disableContextMenu?: boolean;
  banner?: boolean | BannerConfig;
  dom?: DOMContainerConfig;
  fps?: FPSConfig;
  render?: RenderConfig;
  backgroundColor?: string | number;
  callbacks?: CallbacksConfig;
  loader?: LoaderConfig;
  images?: ImagesConfig;
  physics?: object;
  plugins?: PluginObject | PluginObjectItem[];
  scale?: ScaleConfig;,
  instance: Game // It's created internally when the game is initialized
};

public initialize: boolean;

constructor(private api : ApiService){}

initializeGame() {
  this.game = {
    width: "100%",
    height: "100%",
    type: Phaser.AUTO,
    scene: {}
  }
  this.initialize = true
}

getInstance(){
  return this.game.instance
}

from stencil documentation

React

Specific Wrapper

When using a wrapper component, It's not necessary to access the reference directly to configure the game. More details here.

import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'

class App extends Component {
  state = {
    initialize: false,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {}
    }
  }
  render() {
    const { initialize, game } = this.state
    return (
      <IonPhaser game={game} initialize={initialize} />
    )
  }
}

Web Component

Other option is using the web component directly:

import React from 'react'
import ReactDOM from 'react-dom'
import { defineCustomElements as defineIonPhaser } from '@ion-phaser/core/loader'
import Phaser from 'phaser'

const game = {
  width: "100%",
  height: "100%",
  type: Phaser.AUTO,
  scene: {}
}

ReactDOM.render(<ion-phaser ref={el => el.game = game} />, document.getElementById('root'));

defineIonPhaser(window);

from stencil documentation

Vue

In order to use the ion-phaser Web Component inside of a Vue application, it should be modified to define the custom elements and to inform the Vue compiler which elements to ignore during compilation. This can all be done within the main.js file as follows:

import Vue from 'vue';
import { defineCustomElements as defineIonPhaser } from '@ion-phaser/core/loader'

import App from './App.vue';

Vue.config.productionTip = false;
Vue.config.ignoredElements = [/ion-\w*/];

// Bind the IonPhaser custom element to the window object
defineIonPhaser(window);

new Vue({
  render: h => h(App)
}).$mount('#app');

Using IonPhaser in a Vue component

<template>
  <ion-phaser 
    v-bind:game.prop="game"
    v-bind:initialize.prop="initialize"
  />
</template>

<script>
import Phaser from 'phaser'
export default {
  name: 'HelloWorld',
  data() {
    return {
      initialize: false,
      game: {
        width: "100%",
        height: "100%",
        type: Phaser.AUTO,
        scene: {
          init: function() {
            this.cameras.main.setBackgroundColor('#24252A')
          },
          create: function() {
            this.helloWorld = this.add.text(
              this.cameras.main.centerX, 
              this.cameras.main.centerY, 
              "Hello World", { 
                font: "40px Arial", 
                fill: "#ffffff" 
              }
            );
            this.helloWorld.setOrigin(0.5);
          },
          update: function() {
            this.helloWorld.angle += 1;
          }
        }
      }
    }
  }
}
</script>

from stencil documentation

Contributing ✨

When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated ❤️.
You can learn more about how you can contribute to this project in the contribution guide.

Supporting 🍻

I believe in Unicorns 🦄 Support me, if you do too.

Donate Ethereum, ADA, BNB, SHIBA, USDT, DOGE:

Wallet address

Wallet address: 0x3F9fA8021B43ACe578C2352861Cf335449F33427

Please let us know your contributions! 🙏

Enterprise 💼

Available as part of the Tidelift Subscription.

The maintainers of IonPhaser and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Security contact information 🚨

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

License ⚖️

This repository is available under the MIT License.

Happy coding 💯

Made with ❤️

ion-phaser's People

Contributors

jdnichollsc 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  avatar  avatar  avatar  avatar

ion-phaser's Issues

Some functions are missing

I'm trying to use setBoundsRectangle method on Physics arcade body, which is suppose to be available since Phaser 3.20 but it seems this function is missing from this package. I get setBoundsRectangle is undefined. I checked the code of node_modules and indeed, everything related to customBoundsRectangle is missing.
This is the original Phaser https://github.com/photonstorm/phaser/blob/v3.51.0/src/physics/arcade/Body.js#L1165

image

And this is the code from this package
image

Why are some functions missing even though this package is suppose to be using 3.51?

How to load a web picture

to use this.load.image function, How to load a web picture

this.load.image("myhand", "/assets/img/myhand.png");

how to use it ?

please tell me how can I integrate and use it ? phaser is not recognized in react by default

Calling some function from outside

Hello. How could I call some function inside a scene from a component itself? Tried to do something like "this.game.instance.someMethod()" or " this.game.instance.scene.someMethod()" but it gives me error "someMethod() is not a function".
full code:

``
`import { Component, OnInit } from '@angular/core';
import * as Phaser from 'phaser';

@component({
selector: 'app-dancefloor',
templateUrl: './dancefloor.component.html',
styleUrls: ['./dancefloor.component.scss']
})
export class DancefloorComponent implements OnInit {

map = new Array();
initialize = false;
game = {
width: "50%",
height: "50%",
type: Phaser.AUTO,
scene: {
init: function() {
this.cameras.main.setBackgroundColor('#24252A')
},
create: function() {
this.helloWorld = this.add.text(
this.cameras.main.centerX,
this.cameras.main.centerY,
"Hello World", {
font: "40px Arial",
fill: "#ffffff"
}
);
this.helloWorld.setOrigin(0.5);
},
update: function() {
this.helloWorld.angle += 1;
},
someMethod: function () {
this.helloWorld.angle -= 180;
}
},
instance: null
}

constructor(){
}

initializeGame() {
this.initialize = true;

setTimeout(() => {
  console.log(this.game.instance);
  this.game.instance.scene.someMethod();
}, 3000)

}

ngOnInit() {
this.initializeGame();

for(let i=0; i<3; i++){
  let newArr=[];
  for(let j=0;j<5;j++)
  {
    newArr.push(this.generateNewTile());
    console.log('');
  }
  this.map.push(newArr);
  console.log('');
}

}

generateNewTile(isHero:boolean = false) {
return new Tile('1', isHero, this.getRandomInt(1,4));
}

getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}

}

class Tile {
type:string;
isHero:boolean;
score: number;

constructor(type, isHero,collectableItem){
this.type= type;
this.isHero = isHero;
this.score = collectableItem;
}

}
``

React Typescript application this.anything not working

I fixed the interface in the IonPhaser.d.ts file. The interface was missing game so it would through that error. Now I cant seem to fix this.cameras not showing up in the scene part in the state

scene: {
init: function(){
    this.cameras.main.setBackgroundColor('#24252A')
}

Neither does anything that is typed with this. Love to be able to get this working. Love the great work you have already put out thanks!

Failed to parse source map warnings - @ion-phaser/react

After running npm install @ion-phaser/core and npm install @ion-phaser/react. I am successfully able to install both packages. After running my code, which is the following:

import React, { useRef, useState } from 'react'
import Phaser from 'phaser'
import GameScene from './game_scene';
import { IonPhaser } from '@ion-phaser/react'



function Engine() {

    const game = {
        type: Phaser.AUTO,
        width: 800,
        height: 60,
        physics: {
            default: 'arcade',
            arcade: {
                gravity: { y: 200 }
            }
        },
        scene: [GameScene]
      
    }

    const gameRef = useRef(null)
    
    const [initialize] = useState(true)

    // const destroy = () => {
    //     if (gameRef.current) {
    //         gameRef.current.destroy()
    //     }
    //     setInitialize(false)
    // }
    return(
        <>
            <IonPhaser ref = {gameRef} game = {game} initialize={initialize}/>
        </>
        
    )
}

export default Engine;

I get the following warnings/errors:

WARNING in ./node_modules/@ion-phaser/react/dist/components.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\components.ts' file: Error: ENOENT: no such file or directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\components.ts'
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\index.ts' file: Error: ENOENT: no such file or directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\index.ts'
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/react-component-lib/createComponent.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\createComponent.tsx' file: Error: ENOENT: no such file or directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\createComponent.tsx'
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/index.js 1:0-57 1:0-57
 @ ./node_modules/@ion-phaser/react/dist/components.js 6:0-61 9:38-58
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/react-component-lib/createOverlayComponent.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\createOverlayComponent.tsx' file: Error: ENOENT: no such file or 
directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\createOverlayComponent.tsx'
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/index.js 2:0-66 2:0-66
 @ ./node_modules/@ion-phaser/react/dist/components.js 6:0-61 9:38-58
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/react-component-lib/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\index.ts' file: Error: ENOENT: no such file or directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\index.ts'
 @ ./node_modules/@ion-phaser/react/dist/components.js 6:0-61 9:38-58
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/react-component-lib/utils/attachProps.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\utils\attachProps.ts' file: Error: ENOENT: no such file or directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\utils\attachProps.ts'
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/utils/index.js 27:0-30 27:0-30
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/createOverlayComponent.js 46:0-38 89:10-21 131:8-19
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/index.js 2:0-66 2:0-66
 @ ./node_modules/@ion-phaser/react/dist/components.js 6:0-61 9:38-58
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/react-component-lib/utils/case.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\utils\case.ts' file: Error: ENOENT: no such file or directory, open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\utils\case.ts'
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/utils/index.js 28:0-23 28:0-23
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/createOverlayComponent.js 46:0-38 89:10-21 131:8-19
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/index.js 2:0-66 2:0-66
 @ ./node_modules/@ion-phaser/react/dist/components.js 6:0-61 9:38-58
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

WARNING in ./node_modules/@ion-phaser/react/dist/react-component-lib/utils/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\utils\index.tsx' file: Error: ENOENT: no such file or directory, 
open 'C:\Users\gianf\Documents\studio-code\javascript\gfdb-site\gfdb-frontend\node_modules\@ion-phaser\react\src\react-component-lib\utils\index.tsx'
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/createOverlayComponent.js 46:0-38 89:10-21 131:8-19
 @ ./node_modules/@ion-phaser/react/dist/react-component-lib/index.js 2:0-66 2:0-66
 @ ./node_modules/@ion-phaser/react/dist/components.js 6:0-61 9:38-58
 @ ./node_modules/@ion-phaser/react/dist/index.js 1:0-29 1:0-29
 @ ./src/components/engine/index.js 9:0-46 39:35-44
 @ ./src/components/home/index.js 5:0-31 9:30-36
 @ ./src/App.js 5:0-38 13:37-41
 @ ./src/index.js 7:0-24 11:33-36

8 warnings have detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

webpack 5.69.1 compiled with 8 warnings in 18791 ms

React version: ^16.7.0
React-dom: ^16.7.0
How can I fix this?

Cannot find type definition file for 'phaser'

Environment
Angular 9.1.0
Ionic 5.1.0
Typescript 3.7.5

Error Message

[ng] ERROR in node_modules/@ion-phaser/core/dist/types/components/models/index.d.ts:1:23 - error TS2688: Cannot find type definition file for 'phaser'.
[ng] 1 /// <reference types="Phaser" />

I'm getting this error when trying to run ionic serve and I haven't found a solution. I have the file phaser.d.ts in the src folder and have tried to add that directly to tsconfig.json files list without success.

When I remove the line /// <reference types="Phaser" /> from the index.d.ts file in @ion-phaser then it will run but this can't be the solution. Any help is greatly appreciated!

Support React 18

Support React 18

Hello! When trying to use Ion-Phaser React with React 18, I get the following error upon initialization of the IonPhaser component:

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17.

Pointer events shift when scrolling the canvas

I'm using the react package.

When I scroll the page on which the canvas is present after the game has loaded, subsequent calls to pointer.y get shifted by the scroll amount.

My game config:

{
  type: Phaser.AUTO,
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 700,
    height: 700,
  },
  scene: playGame,
}

My jsx:

<IonPhaser
    style={{
      width: '350px',
      height: '350px',
    }}
    key={gameId}
    game={game}
    initialize={initialize}
  />

and the game is basically taken from here.

Edit: After further testing, it's also the case without the position absolute, reflected it in my code.

Loading images in React

I'm making a game where phaser needs to be embedded within a React component. This package seems like a great solution but I'm having trouble loading in images.

I'm hosting a local server using the standard serve command for react, so I know it can't be an access to image file issue.

When loading a png spritesheet I'm getting a black box with a line through it rendering to the screen. I know this means that the image didn't successfully load, so I checked the network tab of my developer tools in the browser. It's showing that it's successfully loading in the resource as an HTML and not as an image.
image

here is the html it is actually getting back from the request
image

here is what is rendering on the canvas
image

here is the code right now

import React from 'react';
import Phaser from 'phaser';
import { IonPhaser } from '@ion-phaser/react';
import './Game.css';

export default class Game extends React.Component {

    constructor(props) {
        super(props);

        // this is where I'm thinking we can take props and use them to build the Phaser scene upon starting a new game
        this.state = {
            unmounted: false,
            initialize: false,
            game: {
                width: 800,
                height: 600,
                type: Phaser.CANVAS,
                physics: {
                    default: 'arcade',
                    arcade: {
                        gravity: { y: 300 },
                        debug: false
                    }
                },
                scene: {
                    init: function () {
                        this.cameras.main.setBackgroundColor('#24252A')
                    },
                    preload: function () {
                        this.load.spritesheet('player', 'assets/spritesheet.png', { frameWidth: 104, frameHeight: 150 });
                    },
                    create: function () {
                        this.helloWorld = this.add.text(
                            this.cameras.main.centerX,
                            this.cameras.main.centerY,
                            "PixelSmash", {
                            font: "40px Arial",
                            fill: "#ffffff"
                        }
                        );
                        this.helloWorld.setOrigin(0.5);
                        this.counter = 0;
                        this.player = this.physics.add.sprite(100, 100, 'player');
                        this.player.setBounce(.2, .2);
                        this.player.setCollideWorldBounds(true);
                        this.physics.world.bounds = new Phaser.Geom.Rectangle(0, 0, 800, 600);

                        this.anims.create({
                            key: 'left',
                            frames: this.anims.generateFrameNumbers('p', { start: 6, end: 12 }),
                            frameRate: 10,
                            repeat: -1
                        });
                    },
                    update: function () {
                        if (this.counter === 0.00) {
                            console.log(this.player);
                            console.log(this.load);
                        }
                        this.counter += .07;
                        this.helloWorld.angle = 0 + (10 * Math.sin(this.counter));
                    }
                }
            }
        }
    }

    initializeGame = () => {
        this.setState({ initialize: true })
    }

    destroy = () => {
        this.setState({ unmounted: true })
    }

    render() {
        const { initialize, game } = this.state
        return (
            <div className="Game">
                <button onClick={this.initializeGame}>start</button>
                {<IonPhaser game={game} initialize={initialize} />}
            </div>
        );
    }
}

The important lines are definitely
this.load.spritesheet('player', 'assets/spritesheet.png', { frameWidth: 104, frameHeight: 150 });
and
this.player = this.physics.add.sprite(100, 100, 'player');

but I don't believe this code to be the issue, as I've tried to do the same with images in a phaser app outside of React and it has worked just fine. I'm probably missing something obvious. Any help would be appreciated.

How do I declare functions in phaser using vue?

I'm following an official Phaser tutorial and so far everything seems to work fine, however in part 8 there's a need to declare a function and use it. Where should I declare functions to be able to use them in phaser? I've tried declaring it inside scene, outside scene, outside game, all of them give me the same error when I run the game - "collectStar is not defined"

import Phaser from "phaser";
var player;
var platforms;
var stars;
var cursors;
export default {
  data() {
    return {
      initialize: false,
      game: {        
        width: 800,
        height: 600,
        type: Phaser.AUTO,
        physics: {
            default: 'arcade',
            arcade: {
                gravity: { y: 300 },
                debug: false
            }
        },
        scene: {
          preload(){
             //preload stuff here
          },
          init() {
          },
          create() {
            /*create stuff here
            ...
           */
            this.physics.add.overlap(player, stars, collectStar, null, this); //getting error on this line
            
          },
          update() {
            /* update stuff here
             ...
            */
          },
//here is the declared function?
            collectStar (player, star)
            {
                star.disableBody(true, true);
            }
        },
      }
    };
  },
  methods: {
    initializeGame() {
      this.initialize = true;
    }
  }
}; 

Next.js: ReferenceError: Phaser is not defined

Tried running the React example directly in my Next.js app, but got the error "window undefined".

To try to solve this problem I loaded Phaser and ion-phaser dynamically, while disabling SSR (i.e., only importing in the client side) as follows, but now get:

index-53dab568.js:593 ReferenceError: Phaser is not defined
at IonPhaser.initializeGame (ion-phaser.entry.js:19)
at IonPhaser.connectedCallback (ion-phaser.entry.js:50)
at safeCall (index-53dab568.js:233)
at fireConnectedCallback (index-53dab568.js:436)
at initializeComponent (index-53dab568.js:405) undefined

import dynamic from 'next/dynamic'

const Phaser = dynamic(
  () => import('phaser'),
  { loading: () => <p>Loading Phaser...</p>,
    ssr: false 
  }
)

const IonPhaser = dynamic(
  () => import('@ion-phaser/react').then((mod) => mod.IonPhaser),
  { 
    ssr: false 
  }
)

const App = () => {

  const state = {
    initialize: true,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {
        init: function() {
          this.cameras.main.setBackgroundColor('#24252A')
        },
        create: function() {
          this.helloWorld = this.add.text(
            this.cameras.main.centerX, 
            this.cameras.main.centerY, 
            "Hello World", { 
              font: "40px Arial", 
              fill: "#ffffff" 
            }
          );
          this.helloWorld.setOrigin(0.5);
        },
        update: function() {
          this.helloWorld.angle += 1;
        }
      }
    }
  }

  return (
    <IonPhaser game={state.game} initialize={state.initialize} />
  )

}

export default App;

Access Vue this from the scene object

Hey there, I'm trying to access the "vue this" inside the scene object where all the magic happens, as to be able to interact between the game and the app. I've tried many ways but can't seem to find a way to properly do it, and the documentation is a bit lacking on the subject.
What's the correct way to get the vue context inside the game component ? Also, is this the right way to create interaction between the two parts ?

Interested making it work with next.js

Hi,

I've tried the package with next.js and couldn't make it work
related issue was described here: #36

yarn create next-app
cd phaser-demo
npm i phaser
npm install @ion-phaser/react --legacy-peer-deps
yarn dev

There are conflicts with react dependencies, hence --legacy-peer-deps option

npm install @ion-phaser/react

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"17.0.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.7.0" from @ion-phaser/[email protected]
npm ERR! node_modules/@ion-phaser/react
npm ERR!   @ion-phaser/react@"^1.3.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/rn/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:

And with the page itself I'm getting navigator is not defined error. I've read some articles about using phaser with pre-rendering react frameworks and they all say "don't" :)

Curious to hear your opinion if it worth effort to get it working with next.js

can not reinitialize after destroy becauseof plugin

I try with a simple example like in this repo, there is not a problem but in my project I use grid-engine plugin, and when I try to initialize after destroy gameRef, this 2 errors occured.

Scene Plugin key in use: GridEngine 
    at ReactComponent (http://localhost:3000/static/js/bundle.js:1437:7)
    at IonPhaser
    at header
    at div
    at IonEx (http://localhost:3000/static/js/bundle.js:409:64)
    at div
    at App
Uncaught TypeError: Cannot read properties of undefined (reading 'create')
    at MainScene.create (ionexample.jsx:50:1)
    at SceneManager.create (phaser.js:84684:1)
    at SceneManager.loadComplete (phaser.js:84615:1)
    at LoaderPlugin.emit (phaser.js:1671:1)
    at LoaderPlugin.loadComplete (phaser.js:165337:1)
    at LoaderPlugin.fileProcessComplete (phaser.js:165311:1)
    at SpriteSheetFile.onProcessComplete (phaser.js:4290:1)
    at data.onload (phaser.js:16548:1)

second error at this line
this.gridEngine.create(cloudCityTilemap, gridEngineConfig);
how can I reinitialize my game after destroy it

Cannot read property 'createElement' of undefined

I did everything as told in Readme. I put something like this in my component

import { React, useState } from "react";
import Phaser from "phaser";
import { IonPhaser } from "@ion-phaser/react";
import { scene } from "./GameScene.js";

export const GamePage = props => {
  let [game, setGame] = useState(null);
  let [init, setInit] = useState(true);

  setGame({
    width: "100%",
    height: "100%",
    type: Phaser.AUTO,
    scene: { scene }
  });

  return (
    <div>
      <IonPhaser game={game} initialize={init} />
    </div>
  );
};

Issue while using with Vue 3 - Canvas not loaded

Hi,

When I try the given example with Vue 3, the canvas is not rendering on the browser. I only see a blank screen. On inspect elements, I see,

<div id="app" data-v-app=""> <ion-phaser game="[object Object]" initialize="true" class="hydrated"> </ion-phaser></div>

However, whenever I change something within the script tag (like adding a comment), the canvas immediately loads on the browser. But then it disappears again if I refresh the browser. I checked with different browsers as well.
Link to the Vue 3 code - not working

But the same code works fine with Vue 2,
Link to the Vue 2 code - working

Can you please tell me what should I do differently for Vue 3? I'm a newbie to programming, so apologies if I'm missing anything obvious. Thanks.

No overload matches

Captura de Pantalla 2020-03-03 a la(s) 9 20 19 p  m

import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonButton, withIonLifeCycle } from '@ionic/react';
import React from 'react';
import Phaser from 'phaser';
import { IonPhaser } from '@ion-phaser/react';

import './Home.css';

class Home extends React.Component {
	state = {
		initialize: false,
		game: {
			width: "100%",
			height: "100%",
			type: Phaser.AUTO,
			scene: {}
		}
	}

	render() {

		const { initialize, game } = this.state;

		return (
			<IonPage>
				<IonHeader>
					<IonToolbar>
						<IonTitle>Hola</IonTitle>
					</IonToolbar>
				</IonHeader>
				<IonContent>			
					<IonPhaser game={game} initialize={initialize} />
				</IonContent>
			</IonPage>
		);
	}
}

export default withIonLifeCycle(Home);

The error occurs when I pass the game object to the game property, I am using Ionic with react. I tried your react example but not working to. I hope that you can help me or is a mistake from my part... Is a blank project with Ionic cli, and I am new using this frameworks sorry for my english, regards.

Scene changing not working

Trying to change one scene from other. After executing

this.scene.start("OtherScene")

just have black screen without any errors. Any help?

  game = {
    width: 600,
    height: 600,
    type: Phaser.AUTO,
    scene: [OtherScene,FirstScene],
    physics: {
      default: 'arcade',
      arcade: {
        gravity: { y: 200 }
      }},
    instance: null
  }


 class FirstScene extends Phaser.Scene{

  constructor() {
    super({key: 'FirstScene'});
  }

  preload() {
...
  }

  create() {
....

    this.input.keyboard.on('keyup_S', ()=>{
      this.scene.start("OtherScene");
    }, this);

  }

class OtherScene extends Phaser.Scene{

  constructor(){
    super({key:'OtherScene'});
  
preload() {
console.log('OtherScene') //not working!!
...
  }
  }

Cannot add 2 different scenes to the game config

Hi, thanks for the work on this.

I am trying out creating a game in react with ion-phaser and I am running into this problem that I cannot add 2 different scenes to the game config.

This is how App.js looks like. I notice that only the last scene in the Array (GameScene) is loaded. If I invert the order in the array, only the other one is loaded.

import React from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'
import { BootScene } from "./BootScene"
import { GameScene } from "./GameScene"

function App() {
  const state = {
    initialize: true,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: [BootScene, GameScene]
    }
  }


  const { initialize, game } = state
  return (
    <div className="App">
      <IonPhaser game={game} initialize={initialize} />
    </div>
  );
}

export default App;

I tried out in a simple HTML with just pure phase and both Scenes are loaded normally.

Here's a simple repo for reproducing:
https://github.com/gilbertoalmeida/ion-phaser-2-scenes

angular demo not work

hello,
first thx thix amazing project

I install the whole project

and go angular demo folder

after npm install -> ng serve

i get this error

ERROR in src/main.ts(3,57): error TS2307: Cannot find module '@ion-phaser/core/loader'.

is there any idea?

thanks you

Property 'ion-phaser' does not exist on type 'JSX.IntrinsicElements'

This code gives error in .tsx file. what is wrong??

`import React from 'react'
import ReactDOM from 'react-dom'
import { defineCustomElements as defineIonPhaser } from '@ion-phaser/core/loader'
import Phaser from 'phaser'

const game = {
width: "100%",
height: "100%",
type: Phaser.AUTO,
scene: {}
}

ReactDOM.render(<ion-phaser ref={el => el.game = game} />, document.getElementById('root'));

defineIonPhaser(window);`

Error: Property 'ion-phaser' does not exist on type 'JSX.IntrinsicElements'

issues with loading and rendering images

Hello,

I have reasons to believe that image.load doesn't actually work.

I have made a testing script and have pasted it below. The ion-Phaser will not render the photo correctly, but instead give a black and green default.

The files are like this:
-React-app
--node_modules/
--Public/
--src/
---App.tsx
---Gamescreen.tsx
---assets/
----logo.png

I have tried multiple variations such as:
./assets/logo.png
logo.png (moved the image to the same folder as app.tsx)
public/assets/logo.png (moved the image and folder into public)

It just doesn't want to render

import React, { useState, useEffect } from 'react'

import Phaser from 'phaser'
import { IonPhaser, GameInstance } from '@ion-phaser/react'

const gameConfig = {
  type: Phaser.AUTO,
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { y: 0 },
      debug: false
    }
  },
  scene: {
    init () {
    this.cameras.main.backgroundColor.setTo(0,255,255);
    this.load.image("bg", './assets/logo.png');
  },

  create () {
    this.add.image(30,30,"bg");
  }
  }
};

export default class Gamescreen extends React.Component {

  constructor(props){
    super(props)
  }

  render() {
    return (
      <IonPhaser game={gameConfig} initialize={this.props} />

    );
  }
}

Using a custom `Phaser.Game` class

Hi! I'm having issues getting this to work with my setup which uses a custom class that extends Phaser.Game (necessary as there's data that needs to be passed into the game and its scenes from React). I noticed that the game is initialized by instantiating a new Phaser.Game directly, but can't find a way to customize this. I'm also a bit confused as to the purpose of the instance prop on the GameInstance type, as instantiating the game externally doesn't allow for the necessary ref to be passed into the game. Is there any way I might be able to get around this?

Thank you so much!

Accessing game instance in React

Hi and thanks for the great work on ion-phaser!
Is there a way to access the Phaser game instance when using React ion-Phaser?
It looks possible in Angular, but after digging through the source and looking up all the examples i could find I'm still at a loss.
I notice it's possible to access the instance from the game config object, but only after it has updated under the hood, so for example:

setTimeout(function() {
    console.log(this.state.game.instance)
}, 1000)

This is obviously a big work around...

is there a correct way already implemented?

Strange Error With Using Spine

Phaser: 3.53.1
Spine: 3.8.95
@ion-phaser/core: 1.2.3

If I used the Spine in Phaser, I will get the error:

Uncaught TypeError: renderer.pipelines.clear is not a function
at SpineGameObjectWebGLRenderer [as renderWebGL] (SpinePlugin.js:35723)

But with out @ion-phaser/core, it's fine.
How could I solved it?
Thanks.

How to upgrade to Phaser 3.52.0

Right now the version of Phaser is freezed at 3.19.0 and I'm getting a lot of errors that, according to the developer, would be solved by upgrading it.

Is there any way to upgrade it?

Support React v17

We have to upgrade this package support React latest version v17.0.2.

As I have an error installing this dependencies using NPM. Fix the upstream dependency conflict

npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"17.0.2" from the root project
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.7.0" from @ion-phaser/[email protected]
npm ERR! node_modules/@ion-phaser/react
npm ERR!   @ion-phaser/react@"*" from the root project
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.```

Sprites Floats Away When Added to Scene Groups

I am using ion-phaser to integrate phaser with react. I cloned the phaser-react example and made minor tweaks.

I created some sprites in a fixed x, y position. However, when I add them to scene group such as

this.group.addMultiple(sprites)

the sprites float downwards out of screen range into infinity. In other words, they slowly move downwards and out of screen range.

Call an Angular function from inside Phaser scene

Hi, I need to call an outside Angular function from inside a phaser scene. Can you please show me the way? I found this [https://www.html5gamedevs.com/topic/35570-calling-an-angular-function-from-within-phaser-3-scene/] :

But nothing said there have worked. It's claimed that it can be done with ion-phaser.

Thanks.

use in Taro

I can’t use this plug-in in taro-react. Does this plug-in support taro-react?

image cannot be loaded

When I introduce resources such as pictures, the picture resources cannot be loaded,(use react)

import React, { Component } from "react";
import Phaser from "phaser";
import { IonPhaser } from "@ion-phaser/react";
import bg from "./assets/img/bg.png";

class App extends Component {
  state = {
    initialize: true,
    game: {
      type: Phaser.AUTO,
      parent: "container",
      width: 500,
      height: 880,
      physics: {
        default: "arcade",
      },
      scene: [
        {
          key: "boot",
          preload() {
            this.load.image("bg", "/src/assets/img/bg.png");
            this.load.image("myhand", "../assets/img/myhand.png");
            this.load.image("button2", "../assets/img/button2.png");
            this.load.image("yanggong", "../assets/img/yanggong.png");
            this.load.image("boom", "../assets/img/boom.png");
            this.load.image("jingong", "../assets/img/jingong.png");
            this.load.image("lock", "../assets/img/lock.png");
            this.load.spritesheet("chance", "../assets/img/chance.png", {
              frameWidth: 53,
              frameHeight: 50,
            });
            this.load.spritesheet("hand", "../assets/img/hand.png", {
              frameWidth: 282,
              frameHeight: 800,
            });
            this.load.bitmapFont(
              "number",
              "../assets/img/number.png",
              "../assets/img/number.xml"
            );
            const percentText = this.make
              .text({
                x: 250,
                y: 400,
                text: "0%",
                style: {
                  font: "18px monospace",
                  fill: "#ffffff",
                },
              })
              .setOrigin(0.5, 0.5);
            this.load.on("progress", function (value) {
              percentText.setText(parseInt(value * 100 + "") + "%");
              console.log(percentText);
            });
            this.load.on("complete", function () {
              percentText.destroy();
            });
            // 屏幕适配
            if (!this.game.device.os.desktop) {
              this.scale.scaleMode = Phaser.Scale.FIT;
              this.scale.refresh();
            }
          },
          create() {
            this.scene.start("start");
          },
          update() {},
        },
        {
          key: "start",
          create() {
            this.add.image(300, 570, "boom");
            this.add.image(250, 400, "bg");
            this.physics.add
              .image(this.game.config.width / 2, 780, "myhand")
              .setScale(0.8, 0.8);
          },
        },
      ],
    },
  };

  render() {
    const { initialize, game } = this.state;
    return (
      <div>
        <IonPhaser game={game} initialize={initialize} />
        {/* <img src={bg}></img> */}
      </div>
    );
  }
}

export default App;

Below is the directory structure
image
Neither path nor absolute path is allowed

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.