Giter Club home page Giter Club logo

phaser-ce's Introduction

Phaser CE (Community Edition)

Phaser CE is a fast, free, and fun open source HTML5 game framework. It uses a custom build of Pixi.js for WebGL and Canvas rendering, and supports desktop and mobile web browsers. Games can be compiled to iOS, Android and native desktop apps via 3rd party tools. You can use JavaScript or TypeScript for development.

Phaser CE is based on Phaser v2.6.2 by Photon Storm. Phaser v3 and Phaser v4 are in active development.

The current Phaser CE release is 2.20.0.

Grab the source and join in the fun!

Contents

Made With Phaser

Thousands of games have been made in Phaser. From game jam entries, to titles by some of the largest entertainment brands in the world. You can find hundreds more on our web site.

We add new games to the Phaser site weekly, so be sure to send us yours when it's finished!

Requirements

Phaser CE requires a web browser that supports the canvas tag. This includes Internet Explorer 9+, Firefox, Chrome, Safari and Opera on desktop. iOS Safari, Android Browser and Chrome for Android are supported on mobile.

While Phaser CE does its best to ensure a consistent cross-platform experience, always be aware of browser and device limitations. This is especially important with memory and GPU limitations on mobile, and legacy browser HTML5 compatibility.

IE9

If you need to support IE9 / Android 2.x and use P2 physics, then you must use the polyfills in the resources/IE9 Polyfill folder. If you don't use P2 (or don't care about IE9!) you can skip this.

JavaScript and TypeScript

Phaser CE is developed in ES5 JavaScript. We've made no assumptions about how you like to code, and were careful not to impose a strict structure upon you. You won't find Phaser CE split into modules, requiring a build step, or making you use a class / inheritance OOP approach. That doesn't mean you can't do so, it just means we don't force you to. It's your choice.

If you code with TypeScript there are comprehensive definition files in the typescript folder. They are for TypeScript 1.4+.

Download Phaser CE

Phaser CE is hosted on Github. There are a number of ways to download it:

NPM

Install via npm:

npm install phaser-ce

Please see additional steps for Browserify/CommonJS and Webpack.

CDN

Phaser CE is on jsDelivr. Include the following in your html:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/phaser.js"></script>

or the minified version:

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

Custom builds are available too, e.g.,

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/custom/phaser-arcade-physics.js"></script>

Getting Started

Our Getting Started Guide will get you up to speed quickly: from setting up a web server to picking an editor/IDE. After that read our Making your first Game tutorial. Please work through this, no matter what your development experience, to learn how Phaser CE approaches things.

Using TypeScript? See Phaser CE's TypeScript definitions and the Using Phaser with TypeScript.

Prefer videos? Zenva have an excellent Phaser video course, with hours of great material.

Source Code Examples

Currently there are over 700 Phaser 2 examples, with the full source code and assets available.

Browse Phaser Examples or clone phaser-examples-mirror and eat your heart out!

Web Templates

If you'd like to try coding in Phaser CE right now, with nothing more than your web browser, open up the Phaser CE Game Template. There are CoffeeScript and ES6 variants too.

http-server

For most development, you'll need to run a local web server. If you already have node, it's as easy as:

npm install -g http-server

Then from your project:

http-server . -c-1 -o

There are many other options that you may already have installed as well.

Browserify / CommonJS

Phaser CE (and Phaser 2, before it) were not written to be modular. Everything exists under one single global namespace, and you cannot require selected parts of it into your builds. It expects 3 global vars to exist in order to work properly: Phaser, PIXI and p2. The following is one way of doing this:

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

If you build a custom version of Phaser CE it will split the 3 core libs out into their own files, allowing you to require them as above.

Full module-based development is available in Phaser v3.

Webpack

As with browserify, use the pixi, p2, and phaser-split modules in build/custom. You can then use expose-loader to expose them as PIXI, p2, and Phaser.

See our webpack project template or lean/phaser-es6-webpack for a sample configuration.

Ionic

See Ionic.

Interphase

Interphase is a programming book for Phaser developers of all skill levels.

With 400 pages of content you'll find detailed articles, game development "Making Of" guides and tutorials.

As well as the book you get all the source code, graphics and assets to go with it, and lots of extras too.

Phaser Editor - A complete Phaser Editor

Phaser Editor is a brand new Eclipse based editor that offers lots of built-in tools specifically for Phaser developers. Handy features include Smart code auto-completion, built-in web server, documentation search, asset management, texture atlas creator, audio sprite creator, asset previews and lots more.

Game Mechanic Explorer

The Game Mechanic Explorer is a great interactive way to learn how to develop specific game mechanics in Phaser. Well worth exploring once you've got your dev environment set-up.

Mighty Editor - Visual Game Editor

MightyEditor is a browser-based visual Phaser game editor. Create your maps with ease, position objects and share them in seconds. It also exports to native Phaser code. Excellent for quickly setting-up levels and scenes.

Building Phaser CE

Phaser CE is provided ready compiled in the build folder of the repository. There are both plain and minified versions. The plain version is for use during development, and the minified version for production. You can also create your own builds.

Custom Builds

Phaser CE includes a grunt based build system, which allows you to strip out features you may not require, saving hundreds of KB in the process. Don't use any Sound in your game? Then exclude the entire sound system. Don't need Keyboard support? That can be excluded too.

As a result of this work the minimum build size of Phaser CE is now just 80KB minified and gzipped.

  1. Run npm install
  2. Run grunt custom to see the module and argument lists (it will error; that's OK)
  3. Run, e.g., grunt custom --exclude=sound,keyboard and then find the built script in dist.

See the Creating a Custom Phaser Build tutorial for details.

Building from source

Should you wish to build Phaser CE from source you can take advantage of the provided Grunt scripts. Ensure you have the required packages by running npm install first.

Run grunt to perform a default build to the dist folder.

Packaging a new release

Releases of new versions of Phaser CE are under the community's control. If you feel there are sufficient fixes, or important ones that warrant a new version release, then please do the following:

  1. Make sure the version number is increased, in line with semver policies, in the following files:

    • package.json
    • src/Phaser.js
  2. Make sure that you have added details of the new version to CHANGELOG.md. This should include a summary of changes made in the version. You can usually obtain this from the commit / PR history. It's nice to credit who made the changes by linking to their GitHub user ID, but isn't a requirement.

  3. From the root repo folder, run grunt eslint and make sure there are no errors. If there are, please fix them, or request that the original author of the code does so.

  4. Once ESLint passes run grunt release, sit back, and wait. It will build all of the versions of Phaser CE required, update the doc files, TypeScript defs and lots more. When finished, commit all of the new files and make sure to include a clear message in your commit saying you want this release pushed to npm. Be sure to tag me when doing this, i.e. 'Phaser CE Version 2.X.X. Please publish to npm @photonstorm' - I'll see it, and then publish as soon as I can (often the same day).

Support Phaser

Developing Phaser takes a lot of time, effort, and money. There are monthly running costs; such as the forum and site, which we maintain 100% ad-free. As well as countless hours of development time, community support, and assistance resolving issues. We do this out of our love for Phaser of course, but at the end of the day there are real tangible costs involved.

If you have found Phaser useful in your development life. Or have made income as a result of using it, and are in a position to support us financially, without causing any detriment to yourself, then please do. There are a number of ways:

It all helps cover our running costs, and genuinely contributes towards future development.

If you would like to sponsor Phaser then please get in touch. We have sponsorship options available on our GitHub repo, web site, and newsletter. All of which receive tens of thousands of eyeballs per day.

Weekly Newsletter

Every Friday we publish the Phaser World newsletter. It's packed full of the latest Phaser games, tutorials, videos, meet-ups, talks, and more. It also contains our weekly Development Progress updates. If you want to know what we're working on, this is the newsletter to read!

Previous editions can found on our Back Issues page.

Contributing

The Contributors Guide contains full details on how to help with Phaser CE development. The main points are:

  • Found a bug? Report it on GitHub Issues and include a code sample.
  • Before submitting a Pull Request run npm run test and fix any errors.
  • Before contributing read the code of conduct.

Written something cool in Phaser? Please tell us about it in the forum, or email [email protected]

Change Log

See Change Log.

License

Phaser CE is released under the MIT License.

Created by

Phaser is a Photon Storm production.

storm

Created by Richard Davey. Powered by coffee, anime, pixels and love.

The Phaser logo and characters are © 2017 Photon Storm Limited.

All rights reserved.

"Above all, video games are meant to be just one thing: fun. Fun for everyone." - Satoru Iwata

Analytics

phaser-ce's People

Contributors

ada-lovecraft avatar alvinsight avatar andrewjb123 avatar beeglebug avatar bitnenfer avatar clark-stevenson avatar cocoademon avatar dependabot[bot] avatar dreaded-gnu avatar englercj avatar fmflame avatar georgiee avatar hexus avatar jcd-as avatar martinlindhe avatar mason-stewart avatar nhowell avatar phaiax avatar photonstorm avatar pixelpicosean avatar pjbaron avatar pnstickne avatar rblopes avatar rroylance avatar samid737 avatar samme avatar stoneman1 avatar vbornand avatar vforsh avatar wseng 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  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

phaser-ce's Issues

Requesting PVRTC texture loading for Phaser.Loader#atlas

Feature Request

Firstly, thanks so much for this great and well-documented library!

Currently there is the beautiful option of loading PVRTC (or other compressed texture formats) with Phaser.Loader#image [1] and Phaser.Loader#texture [2].

However my preferred way of loading spritesheets with frames for animation is via Phaser.Loader#atlasJSONHash [3], but this method only accepts a normal image file along with the atlas data file (in JSON format).

I suppose my question is: how can we support an object with compressed texture formats (and a fallback truecolor image file as an argument passed to the Phaser.Loader#atlasJSONHash method? Is this desirable behavior for anyone else?

BitmapFont from cache.addBitmapFontFromAtlas() does not render well

This issue is about how BitmapFonts that are created from a texture atlas ( via cache.addBitmapFontFromAtlas() ) look very ugly compared to normal BitmapFonts ( this.load.bitmapFont() ) that use a separate non-atlas-merged PNG file.

The font PNG and XML are created using Littera. The font PNG is merged with other images into a texture atlas using TexturePacker. I am also using Phaser.CANVAS renderer.

The BitmapFont from the texture atlas is noticeably jagged / cropped on some parts / not smooth.

bmfont_issue

cache.addBitmapFontFromAtlas() is a very nice and handy feature as I am able to merge all my fonts into one texture atlas, however I currently can't use it in my game because it doesn't render so well. I would appreciate a fix for this. :)

Duplicate touch events on Android

When switching to v2.7.3, I have noticed strange behavior on Android where each touch event would trigger twice. Doing some debugging, I discovered that both the mspointer and touch device pointer types were being registered, and both would fire their own event when a touch event occurred.

I'm not sure why I did not encounter this in previous versions, but I suspect it has something to do with the move towards using the W3C version of PointerEvents rather than the old msPointer API:

6caec0d

Both the MSPointer class docs, as well as the code, suggest this is intended for use on Windows devices only, but window.PointerEvent is supported cross-platform, at least in Chrome. I'm not too familiar with the API, but I suspect the old window.navigator.(ms)PointerEnabled variables were returning true only on Windows devices, even on Chrome, which would explain why this problem didn't occur until the commit linked above. I also don't understand why I don't see double events on desktop Chrome, as it should be registering the pointer there as well...

As such, I'm not sure of the proper fix. One way would be to ensure that Phaser only ever registers one touch device handler, but if so, which should it prioritize? Another option would be to do a Windows OS check before setting mspointer, with a note that a better fix will come at a later date. This would adhere to the documented behavior of MSPointer and avoid any confusion caused by MSPointer being used on platforms other than Windows. (I would guess Phaser 3 would be the place to do any serious refactoring to make PointerEvent truly a cross-platform input option.)

Sound duration is zero after loaded and decoded

Description
After loading an MP3 sound and waiting for decodedCallback than getting the sound duration returns zero (0) value.

Affected source
https://github.com/photonstorm/phaser-ce/blob/v2.7.3/src/sound/Sound.js
(I think the issue covers the same case as handled with CocoonJS, take a look at line 704)

Environment:
Phaser: 2.7.3-CE
OS: Windows 7
Browser: Firefox 51 (64-bit)

Code example

preload

function preload() {
    game.stage.backgroundColor = '#85b5e1';
    game.load.baseURL = 'http://examples.phaser.io/assets/';
    game.load.crossOrigin = 'anonymous';
    game.load.audio('audio_test', 'audio/tommy_in_goa.mp3');
}

create

var audio;
function create() {
    audio = game.add.audio('audio_test');
    game.sound.setDecodedCallback(['audio_test'], function() {
        console.log(audio.duration);  // BUG: sound  duration is zero (0)!
        audio.play();
        audio.stop();
        console.log(audio.duration);  // BUG solution: sound duration is > 0
    }, this);
}

http://phaser.io/sandbox/LDjSQJNv

Error TypeScript def getTileX

  • An error in the TypeScript defs

in phaser.comments.d.ts 29577:
getTileX(layer: Phaser.TilemapLayer|Phaser.TilemapLayerGL, x: number): number;

in phaser.js line 98574::
Phaser.TilemapLayer.prototype.getTileX = function (x) {

// var tileWidth = this.tileWidth * this.scale.x;
return Math.floor(this._fixX(x) / this._mc.tileWidth);

};

same happens for getTileY.

Correct way of adding typescript def files in version ce ?

Hi,

I am using webpack with expose-loader to have Phaser etc available on the global scope. Things are working well, I decided to upgrade to phaser-ce and the only way I could get my IDE (webstorm) to recognise that Phaser was actually a type was doing the following in MY tsconfig.json file

  "include": [
    "**/Game.ts",
    "../node_modules/phaser-ce/typescript/phaser.d.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]

Now it does work but says there are Multiple Options i.e. phaser.d.ts and phaser.comments.d.ts and phaser_box2d.d.ts.

I was wondering if I was doing the above correctly ?

I of course decided to remove the Includes section above but then that fails probably due to the fact that I have the exclude node_modules so the types are never being picked up.

I am using typescript 2.1 and decided to try and use the typeRoots but this also failed

"typeRoots" : ["../node_modules/phaser-ce/typescript"]

I am little confused of how to proceed do I leave the "../node_modules/phaser-ce/typescript/phaser.d.ts" inside the include section of the tsconfig.json ? It just feels kind of wrong.

Also even if I use this way then 'Phaser' seems to show Multiple Implementations for Phaser

Any help or info really appreciated

Thanks

Enable github pages for the `docs/` directory?

The website http://phaser.io/docs suggests:

These docs are for Phaser 2.6.2
If you're using Phaser CE then download the CE repository and open docs/index.html

And since GitHub now supports docs/ directory for zero config github pages, can we turn that on for easier documentation viewing?

body.setCircle offsets

The offset parameters in body.setCircle appear not to work. No matter what I set the values to, the debug hit boxes shown are the same.

sprite.body.setCircle(32, 100, 300);

Tried in version 2.7.3.

GL ERROR :GL_INVALID_OPERATION : glDrawElements: Source and destination textures of the draw are the same.

I recently switched from phaser to phaser-ce and everything worked quite nicely except this error.

I've pinpointed it to when I apply a filter to two different sprites using the same texture. That is, something like this:

const s1 = this.game.add.sprite(0, 0, 'spriteKey');
const s2 = this.game.add.sprite(20, 20, 'spriteKey');

const filter1 = new Filter(this.game, null, shaderSource);
const filter2 = new Filter(this.game, null, shaderSource);

s1.filters = [ filter1 ];
s2.filters = [ filter2 ];

The error looks like this:
screen shot 2017-02-23 at 12 57 38

It doesn't occur in phaser 2.6.2.

It also messes up some rendering. Sprites which use the same key are flashing and teleporting seemingly at random.

The main difference I have been able to find between phaser and phaser-ce is the multi texture feature described in the tutorial. It also seems logical as sprites seem to affect each other. I have no idea how though.

How can I further debug this issue?

Weapon.trackRotation does not track world rotation, but offset does

This Issue is about (delete as applicable)

  • A bug in the API - 2.7.3

Bug here - https://github.com/photonstorm/phaser-ce/blob/master/src/plugins/weapon/WeaponPlugin.js#L879

I have a gun that is a child (via addChild) of a sprite. When the sprite moves, the gun rotates with it, but the fired bullets do not. I believe it is due to that line, where the local angle is used instead of the world angle.

Switching it from

this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.rotation);

to

this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.worldRotation);

should fix it

Videos don't play properly under iOS 10.2

Videos seem to only download up to the canplaythrough point (?) on iOS 10.2. Videos show the preview image fine, and download the first second or two of the video (possibly up to canplaythrough), they don't unlock, but can be clicked to play. After the first couple of seconds of video, the video freezes – though the audio continues playing. Note, this works fine with iOS 9.3, loading and playing the whole video.

Here the most basic example I could show

    var game = new Phaser.Game(1366, 768, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create })

    game.stage.scaleMode = Phaser.StageScaleMode.EXACT_FIT

    function preload() {
      game.add.text(100, 100, "Loading videos ...", { font: "65px Arial", fill: "red" })
      game.load.video('test', 'test.mp4')
    }

    function create() {
      var video = game.add.video('test');
      video.play(true);
      video.addToWorld();
    }

This has been tested using CE 2.7.3.

I have tried this with iPads and the xcode simulator using both iOS 9.2 and iOS 10.3. Both show the same behaviour for the respective OS.

This Issue is about (delete as applicable)

  • A bug in the API (CE 2.7.3)

I've put a demo up here.

Source for the above demo can be download here.

The behaviour can also be seen on the Phaser demo site

Sound issues with 2.7.4+ release

This Issue is about a bug in the API (Sound).
I think the last modification to the Sound class (5735dbf) resulted in some kind of regression.
I'm trying to play the same audio file sequentially using the forceRestart parameter but I'm noticing silent gaps in the sequence, so the sound is not always playing.
No problems using 2.7.3.
I will try to create some kind of minimal example.

Tweens with multiple TweenData in their timelines lag behind tweens with only 1 TweenData in their timelines

This Issue is about: A bug in the API (CE 2.7.3 - also seen in Phaser 2.6.2)

https://jsfiddle.net/uua222wh/1/

I'm creating a game that relies on multiple different layers running running synchronised tweens to animate composite sprites. It seems that a tween made up of multiple TweenData (i.e. one created using lots of calls to Tween.to()) will run significantly slower than a tween made up of less TweenData. I've created an example above. The two animations should each take 1000ms to complete, but they rapidly skew out of synch.

Basically it seems that the larger the value of a tweens's timeline.length, the longer the tween takes to animate.

Edge Browser Compatibility

Running Phaser in chrome works great, but I am seeing some errors thrown in Edge (syntax errors, inputs not being processed, etc.). Are there any goals to bring Edge support in line?

Phaser.Text is using Object.assign, which is an ES6 feature

This Issue is about (delete as applicable)

  • Compatibility with older browsers

Without any polyfill, this will fail on some older browsers (e.g. Android 4.4 default browser/webview).

We should change the use of Object.assign to Phaser.Util.extend instead.

2.7.4 ReadMe summary is out of date

  • An error in the documentation

Looks like none of the PRs have updated the ReadMe for a couple of months now. I'm at fault here too. Can we update the summary so everyone can understand what 2.7.4 is changing/fixing? What should go there - author/commit/PR link?

Android Chrome Version 56.0.2924.87 FullScreen Problem

After realise phaser-ce v2.7.3 i try to use fullScreenAPI on Android Chrome and it doesn't work for me,

if(game.scale.isFullScreen == false){
this.fullScreenButton.alpha = 0;
game.scale.startFullScreen(false);
} else {
game.scale.stopFullScreen();
this.fullScreenButton.alpha = 1;
}

By the way, the same codes works for phaser 2.6.2. I change and test it.
Can you guys check for it :)

Name field in bower.json

Was wondering if bower.json needs updating, should it be "name": "phaser-ce" - so as to not conflict with Phaser 2.7?

Phaser.Cache.destroy() does not destroy cached items

This Issue is about a bug in the Phaser.Cache API 2.7.3 and below.

In method Phaser.Cache#destroy

/**
 * Clears the cache. Removes every local cache object reference.
 * If an object in the cache has a `destroy` method it will also be called.
 *
 * @method Phaser.Cache#destroy
 */
 destroy: function () {
   // ...
}

The unexpected behaviour is that most objects that are put in the cache are wrapped in another object, without a destroy method.

For example, looking at BitmapData, which has a `destroy' method:

  • addBitmapData stores the actual data in a new object with keys data and frameData
  • getBitmapData relies on getItem to get the correct data from the cache
  • destroy does not take the property into account as getItem does and therefore does not invoke destroy on the data and frameData objects.

As a result, in this case, canvasses are never returned to the CanvasPool, causing a memory leak when loading external image data and relying on the cache to clean up old images.

Suggested solution:

  • Update the destroy method to also iterate over the properties in the stored cache object. If a property contains a destroy method, invoke it on the property as well.

Weapon.KILL_WORLD_BOUNDS not working

This Issue is about (delete as applicable)

  • A bug in the API (phaser-ce 2.7.3)
  • A problem with my own code

I tried to reproduce here but it seems to be working fine. Not sure what is causing this issue in my code - if it's me or Phaser.

In my code I set up multiple weapons for each sprite and set them all to autoFire. I was noticing really bad performance and eventually found that my custom Bullet classes are not having their kill() function called when going out of bounds (but it is called the in the collision handler just fine).

workaround

Include the following in my custom bullet classes' constructor

    this.checkWorldBounds = true;
    this.outOfBoundsKill = true;

Here is my weapon setup code

  _setupWeapons() {
    //add all the weapons from the json file
    this.weapons = [];
    const leveledWeapon = this.info.weapons['low_level'];
    for (var i in leveledWeapon) {
      const weaponInfo = leveledWeapon[i];
      const ammo = weaponInfo.preallocation || 20; 
      var weapon = this.game.plugins.add(Phaser.Weapon);
      weapon.bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
      weapon.bulletSpeed = weaponInfo.bulletSpeed || 500;
      weapon.fireAngle = this._getWeaponAngle(weaponInfo.angle);

      weapon.bulletClass = Ship._getBulletClass();
      weapon.createBullets(ammo);
      weapon.autoExpandBulletsGroup = true; 
      console.log(weapon.bullets.children)

      weapon.fireRate = weaponInfo.fireRate || 500;
      //weapon.dmg = this.getDamage();
      weapon.dmg = 25; //this does nothing right now
      weapon.bullets.myWeapon = weapon;

      const percentOffset = (weaponInfo.xPercentOffset || 0) / 100;
      const xPixelOffset = Math.abs(this.width) * percentOffset;
      const yPixelOffset = -this.anchor.y * this.height + this.height / 2; //regardless of anchor, bullets start in middle Y of sprite
      weapon.trackSprite(this, xPixelOffset, yPixelOffset);

      this.weapons.push(weapon);
    }
    console.log(this.weapons)

  }

grunt tsdocs Task Fails 2.7.3

Running grunt tsdocs (which is part of the release task as well) fails currently with

Warning: Cannot read property 'text' of undefined Use --force to continue.

My guess is a previous commit did not fully conform to the requirements put forth by tsdocs and is now causing it to fail, though I've yet to locate which file is the source of this problem. I'm still actively looking, but additional eyes are appreciated!

MultiTexturing after 2.7.3.

Using multiple spritesheets in the game causes too many drawCalls, even having >5 drawCalls means on devices it runs below 30fps. In phaser 2.7.0 -> 2.7.2, using MultiTexture support fixed this issue on Desktops/Android devices but on iOS, a lot of textures were replaced with solid Magenta. When 2.7.3 was released, this "fixed" this issue, but now it just doesn't seem to be working on most devices at all.

I've looked through and put console logs into phaser-ce/src/pixi/renderers/WebGLRenderer.js to look, and it seems that on my desktop, the maxTextureSpaceAvailable is more than enough to fit all spritesheets with lots of space leftover, but even on my Samsung S7, the maxTextureSpaceAvailable is at 0 before even getting to adding any spritesheets into the texture cache.

My first test i attempted was to just remove the limit making sure maxTextureSpaceAvailable was above 0, and to my surprise, on my S7, the game ran at 60fps with a single draw call, even with this value dropping below zero...

if (maxTextureAvailableSpace <= 0) { base.textureIndex = 0; } else { base.textureIndex = (1 + (index % (maxTextures - 1))); }

Seems a bit weird that it could drop below zero, i'm not very knowledgeable about working directly with WebGL, but initial thoughts were that maybe the reported value of var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); might be incorrect... though i'm honestly not 100% on that.. however my happiness of 'fixing' this was short-lived as the game just doesn't work on iOS now, obviously things are very different between the two.

Even if its something i'm personally doing wrong in my code, it seems wrong that on Android i can add things to the textureCache which exeeds the Max_Texture_Size and it works fine, 60fps.. but not on iOS. I'll keep looking personally as having a high FPS on devices are very important to my project, and the multiple spritesheets are essential for supporting multiple languages, but potentially something not working right here that someone could take a look at?

Error importing phaser using typescript in Ionic2

I was trying to use phaser in a Ionic2 application.
When I try to import phaser I get the following error:

File '.../node_modules/phaser-ce/typescript/phaser.comments.d.ts' is not a module.

Even vscode warns me there's something wrong with the import statement.

2017-03-03 4
capture

Here's the code:

import { Component } from '@angular/core';

import { NavController } from 'ionic-angular';

import {Phaser} from 'phaser-ce';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {
    
  }

Can anyone help me resolve this issue?

load complete & reset order

This Issue is about (delete as applicable)

  • A bug in the API @ HEAD

Hey folks,

My team working with phaser had just found what we believe to be an issue - and we wanted to make sure that this isn't "as designed". If it is as designed, we would be interested to hear the justifications for the order in which these calls are made.

Assuming we load in preload, and also (as per our game design) perform a load in the create method: the load performed in the create function doesn't work.

See the following code from src/loader/Loader.js

finishedLoading: function (abnormal) {

        if (this.hasLoaded)
        {
            return;
        }

        this.hasLoaded = true;
        this.isLoading = false;

        // If there were no files make sure to trigger the event anyway, for consistency
        if (!abnormal && !this._fileLoadStarted)
        {
            this._fileLoadStarted = true;
            this.onLoadStart.dispatch();
        }

        this.onLoadComplete.dispatch();

        this.game.state.loadComplete();

        this.reset();

    },

It's our understanding that this.reset() should be called before any of the complete callbacks are dispatched, not after. Otherwise we're clearing the loading state after we've claimed to already be done with the loading state.

With the code as it is: the preload performs some loading calls. Once complete it dispatches these complete callbacks which trigger the create method. Our create method requests some assets to be loaded. Then the finishedLoading callback from the preload state calls this.reset() which will falsely clear the isLoading flag, even though the create method has requested that some assets be loaded.

Our proposed fix would be:

finishedLoading: function (abnormal) {

        if (this.hasLoaded)
        {
            return;
        }

        this.hasLoaded = true;
        this.isLoading = false;

        // If there were no files make sure to trigger the event anyway, for consistency
        if (!abnormal && !this._fileLoadStarted)
        {
            this._fileLoadStarted = true;
            this.onLoadStart.dispatch();
        }

        // clear loading state before we claim loading is complete
        this.reset();

        this.onLoadComplete.dispatch();
        this.game.state.loadComplete();

    },

As @photonstorm and others have mentioned many times in forms: there are many workarounds to loading failing in the create method. Our team is simply proposing what we think would be a more obvious flow that would avoid the issue all together.

Let us know what you think. :-)

Thanks,
Jared

[TS] Optional parameters for Phaser.Group.addAll()

This Issue is about : an error in the TypeScript defs

( Phaser v. 2.6.2)

Just converted my project into typescript and I hit couple of TS errors while trying to update some values for all my Phaser.Group elements using .addAll() method.

Below example should throw an error

this.asteroidsWave.addAll('angle', this.game.rnd.integerInRange(1,4));

Error:
error TS2346: Supplied parameters do not match any signature of call target.

working example:

this.asteroidsWave.addAll('angle', this.game.rnd.integerInRange(1,4), false, false);

After reading the TS definitions in phaser.d.ts , it turned out that the last two parameters aren't optional , which I think they should be , cause when they're not defined they're implicitly changed to false.

phaser.js

33358: Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) {
    if (checkAlive === undefined) { checkAlive = false; }
    if (checkVisible === undefined) { checkVisible = false; }
    if (force === undefined) { force = false; }

phaser.d.ts
1768: addAll(property: string, amount: number, checkAlive: boolean, checkVisible: boolean): void;

Either setting the default values for last two parameters or making them optional should fix the error.

addAll(property: string, amount: number, checkAlive?: boolean, checkVisible?: boolean): void;
or

addAll(property: string, amount: number, checkAlive: boolean = false, checkVisible: boolean=false): void;

emitter setXSpeed/setYSpeed does not work

This Issue is about (delete as applicable)

  • A bug in the API (always say which version you're using!)

this code does not work correctly.
particles can not move anywhere. (works in phaser 2.6.2)

        this.waterParticle = game.make.bitmapData(2, 2);
        this.waterParticle.rect(0, 0, 2, 2, '#ff0000');
        this.waterParticle.update();

        this.emitter = game.add.emitter(200, 200, 500);
        this.emitter.makeParticles(this.waterParticle);
        this.emitter.setXSpeed(-100, -250);
        this.emitter.setYSpeed(-100, 100);
        this.emitter.setAlpha(0.2, 1);
        this.emitter.flow(500, 20, 2, -1, true);

Missing comments in the phaser.comments.d.ts file in release v2.7.3

Hi Phaser Team,

I have updated from v2.7.2 to the latest v2.7.3 and detected that the typescript/phaser.comments.d.ts has no longer any comments. I find them realy helpfull. I have taken a look into the master branch and it is still without comments.

unfortunately the v2.7.2 tag does not exists here.
I have used npm for installing it.

best regards
Alex

Box2d debug render doesn't follow world scale and rotation.

Box2d debug render doesn't follow world scale and rotation.

Current version:

/**
    * Renders 'debug draw' data for the Box2D world if it exists.
    * This uses the standard debug drawing feature of Box2D, so colors will be decided by
    * the Box2D engine.
    *
    * @method Phaser.Utils.Debug#box2dWorld
    */
    box2dWorld: function () {
    
        this.start();
        
        this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0);
        this.game.physics.box2d.renderDebugDraw(this.context);
        
        this.stop();

    }

Improved version:

/**
    * Renders 'debug draw' data for the Box2D world if it exists.
    * This uses the standard debug drawing feature of Box2D, so colors will be decided by
    * the Box2D engine.
    *
    * @method Phaser.Utils.Debug#box2dWorld
    */
    box2dWorld: function () {

        this.start();

        this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0);
        this.context.scale(this.game.camera.scale.x, this.game.camera.scale.y);
        this.context.rotate(this.game.world.rotation);
        this.game.physics.box2d.renderDebugDraw(this.context);

        this.stop();

    },

Invalid pointer world position when camera/world scale is not 1 or world rotation is not 0

If world scale is not 1 or rotation is not 0 pointer world position will be invalid.

Sample code:

var sprite;

function preload() {
    game.load.baseURL = 'http://examples.phaser.io/assets/';
    game.load.crossOrigin = 'anonymous';
    game.load.image('phaser', 'sprites/phaser-dude.png');
}

function create() {
    game.world.position.set(100,100);
    if (1)
    {
        game.world.scale.set(0.5,0.5);
    }
    if (1)
    {
        game.world.rotation = Math.PI * 45 / 180;
    }
    sprite = game.add.sprite(0, 0, 'phaser');
    sprite.anchor.set(0.5, 0.5);
}

function update() {
    var pointer = game.input.mousePointer;
    sprite.x = pointer.worldX;
    sprite.y = pointer.worldY;
}

Temporary workaround:

var sprite;

function preload() {
    game.load.baseURL = 'http://examples.phaser.io/assets/';
    game.load.crossOrigin = 'anonymous';
    game.load.image('phaser', 'sprites/phaser-dude.png');
}

function create() {
    game.world.position.set(1000,1000);
    if (1)
    {
        game.world.scale.set(0.5,0.5);
    }
    if (1)
    {
        game.world.rotation = Math.PI * 15 / 180;
    }
    sprite = game.add.sprite(0, 0, 'phaser');
    sprite.anchor.set(0.5, 0.5);
}

function update() {
    var pointer = game.input.mousePointer;
    var camera = game.camera;
    var world = game.world;
    var rotation = -world.rotation;
    var sin = Math.sin(rotation);
    var cos = Math.cos(rotation);
    var tmpX = (pointer.x + camera.position.x) / camera.scale.x;
    var tmpY = (pointer.y + camera.position.y) / camera.scale.y;
    var worldX = tmpX * cos - tmpY * sin;
    var worldY = tmpX * sin + tmpY * cos;
    sprite.x = worldX;
    sprite.y = worldY;
}

Display child sprite behind parent sprite

This Issue is about (delete as applicable)

  • A bug in the API - 2.7.3

I'm trying to get some guns to appear behind their parent sprite, and this thread leads me to believe it's not possible without a hacky work around. Is this true? If it is, how can we enable support for rendering parent sprite on top of children?

Compressed texture problem

In src/loader/Loader.js on line 2297 you have :

 case 'texture':

                if (file.key.split('_').pop() === 'truecolor')
                {
                    this.loadImageTag(file);
                }
                break;

i think there should be something like this :

 case 'texture':

                if (file.key.split('_').pop() === 'truecolor')
                {
                    this.loadImageTag(file);
                } else {
			  // load pvr files.	
                           this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
			 }
                break;

or simply remove break; before case 'binary':

Incorrect rendering of tinted character in BitmapText with Canvas renderer

This Issue is about

  • A bug in the API (checked from 2.6.1 on)

When using multiple tinted BitmapTexts some characters may be rendered incorrectly. It can even lead to IndexSizeError in some browsers.

On image below is test scenario:

bitmaptextbug

Two BitmapTexts are used to show number 5. Then, when both texts are changed to 10, only first (bottom one) text is rendered correctly, while the second has distorted "50" instead of 10. Problem is related only to Canvas renderer.
Problem is that both texts use the same character and parameter requiresReTint is not on glyph, but on texture. Then tinted texture for first character occurence is updated, but not for other characters sharing the same texture (as requiresReTint is flagged to false after first retint). So, second text uses old tinted texture, but tries to display correct rectangle from it. If rectangle to display is bigger than tinted texture, you may get IndexSizeError in some browsers (IE).

Solution working for me was to change (https://github.com/photonstorm/phaser-ce/blob/master/src/gameobjects/BitmapText.js#L455):

            g.scale.set(scale);
            g.tint = this.tint;
            g.texture.requiresReTint = true;

to:

            g.scale.set(scale);
            g.tint = this.tint;
            g.texture.requiresReTint = true;
            g.cachedTint = 0xFFFFFF;

Arcade.Body.reset() sizes bodies of scaled sprites incorrectly

http://codepen.io/samme/pen/apJBWP?editors=0010

  • A sprite with a physics body and exists = false
  • Modify its scale
  • Call sprite.reset(…) or sprite.body.reset(…)
  • The body dimensions don't match the sprite dimensions

This can happen if you try scaling weapon bullets (which don't exist until they are reset when fired).

It happens because

  • sprite.reset() → body.reset() updates the cached scale but doesn't resize the body
  • body.preUpdate() → body.updateBounds() resizes the body only if the cached scale is wrong

This issue is about (delete as applicable)

  • A bug in the API (2.6, 2.7)

Changing game volume when sound is muted will unmute the sound but `game.sound.mute` stays `true`

This Issue is about: A bug in the API
Reproduced with: 2.6.2 and CE 2.7.3
Description: Changing game volume when sound is muted will unmute the sound but game.sound.mute stays true
Sandbox example: http://phaser.io/sandbox/edit/pwRPKVcR

I could understand that changing volume unmutes the game but it then should also revert mute to false.

My workaround currently:

({
  vc_updateVolume: function() {
    var nv, was_muted;
    nv = this.vc_getVolume();
    if (nv !== this.game.sound.volume) {
      was_muted = this.game.sound.mute;
      if (was_muted) { this.game.sound.mute = false }
      this.game.sound.volume = nv;
      if (was_muted) { this.game.sound.mute = true }
    }
  }
});

// ---
// generated by coffee-script 1.9.2

Update to 2.7.4 instant crash: Uncaught TypeError: this.preUpdateLifeSpan is not a function

This Issue is about (delete as applicable)

  • A bug in the API (always say which version you're using!)
Uncaught TypeError: this.preUpdateLifeSpan is not a function
    at Phaser.Image.preUpdate (phaser.js:34431)
    at Phaser.Stage.preUpdate (phaser.js:16669)
    at Phaser.Game.updateLogic (phaser.js:21276)
    at Phaser.Game.update (phaser.js:21167)
    at Phaser.RequestAnimationFrame.updateRAF (phaser.js:48928)
    at _onLoop (phaser.js:48911)
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.Image#preUpdate
* @memberof Phaser.Image
*/
Phaser.Image.prototype.preUpdate = function() {

    if (!this.preUpdateInWorld() || !this.preUpdateLifeSpan())
    {
        return false;
    }

    return this.preUpdateCore();

};

Looks like it's probably related to #63

PIXI is not defined (Ionic 2)

Hello, I am trying to create a phaser application using Ionic 2. All that is do is initialize an ionic 2 project using ionic start then once that is created I do a npm install phaser-ce --save Once that finished I import phaser into one of the auto generated pages like so.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import Phaser from 'phaser-ce'
@Component({
  selector: 'page-page1',
  templateUrl: 'page1.html'
})
export class Page1 {
  constructor(public navCtrl: NavController) {  }
     ionViewDidLoad(){
        console.log(Phaser)
     }
}

Then I simply just try to run the application. When i do i get this error
pixi erorr

By going into the developer console on chrome this is where the error is coming from
chrome error

I have tried editing the files to make this work but no matter what i do nothing seems to work. If anyone knows if this is a bug or if I am just doing something wrong that would be great.
Thank you.

ScaleManager Issues with Google Fonts

For reference, I posted this in the forums

I am using the latest phaser ce build, phaser 2.7.3. My target browser is desktop Chrome
(I don't care much for any other browser, mobile platform, etc)

Explanation of my issue: I have a text, at position (0,0) [Therefore, no possibility of it no being a whole number, etc]. It is not scaling properly.

=> Minimal fiddle testcase showing my problem: http://jsfiddle.net/1g3cj8md/

=> Expected outcome if game is not scaled: http://jsfiddle.net/encznmqq/1/

Is this a bug? Am I missing anything? Basically, the rendering of a google fonts when the game is scaled seems off. This happens whether you use a pixel-friendly font like VT323 or a more 'normal' font.
I pressume that if this is a bug, it has to do with how scaling manages text. Perhaps a workaround is using other types of fonts?

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.