Code Monkey home page Code Monkey logo

photonstorm / phaser Goto Github PK

View Code? Open in Web Editor NEW
36.7K 1.2K 7.1K 394.69 MB

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.

Home Page: https://phaser.io

License: MIT License

JavaScript 99.52% GLSL 0.23% TypeScript 0.24%
phaser phaserjs javascript html5-game-development webgl game-frameworks game-development gamedev canvas phaser-development facebook-instant-games

phaser's Introduction

Phaser - HTML5 Game Framework

Phaser Header

Discord JSDelivr GitHub

Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop and mobile web browsers. Games can be compiled to iOS, Android and native apps by using 3rd party tools. You can use JavaScript or TypeScript for development.

Along with the fantastic open source community, Phaser is actively developed and maintained by Phaser Studio Inc. As a result of rapid support, and a developer friendly API, Phaser is currently one of the most starred game frameworks on GitHub.

Thousands of developers from indies to multi-national digital agencies, along with universities worldwide use Phaser. Take a look at their incredible games in our showcase video:

Phaser Games Showcase video

Visit the Phaser website
Play some amazing games
Learn By browsing our API Docs, Support Forum and StackOverflow
Code Examples? We've over 2000 Examples to learn from
Read the weekly Phaser World Newsletter
Be Social: Join us on Discord and Reddit or follow us on Twitter

Grab the source and join the fun!

What's New

21st June 2024

The Phaser Studio team have been hard at work on the v3.85 release, which went into beta today. This release builds upon the improvements made in v3.80 and brings lots more fixes and updates to the party. We send our thanks to the Phaser community for their help in both reporting issues and submitting pull requests. You lot always keep us on our toes πŸ™‚

In parallel we've also been busy working on a replacement physics engine and a brand new renderer, built from the ground-up to be as efficient and powerful as possible for 2D web games. Keep track of everything in our weekly newsletter Phaser World.

Phaser also hit 36,500 stars on GitHub and is used by over 34,600 developers. These figures are a testament to the growing community who has embraced Phaser as their go-to framework for web game development. We're grateful for the support and feedback we've received, and we're committed to continuing to evolve Phaser to meet your needs.

Phaser wouldn't have been possible without the fantastic support of the community. Thank you to everyone who supports our work, who shares our belief in the future of HTML5 gaming, and Phaser's role in that.

Happy coding everyone!

Cheers,

Rich and the team at Phaser Studio
@photonstorm

boogie

Download Phaser

Phaser is available via GitHub, npm and CDNs:

NPM

Install via npm:

npm install phaser

Create Phaser Game App

One of the easiest ways to get started quickly with Phaser is by using our new create-phaser-game app. This is a CLI tool that presents an interactive selection of official project templates and demo games. Just issue the command, answer some questions and the app will download and configure the right package for your needs.

Currently, we support all of the following frameworks and bundlers:

Frameworks Bundlers
Vue.js Vite
React Rollup
Angular Parcel
Next.js Webpack
SolidJS ESBuild
Svelte Import Map
Remix Bun

Most of these come in both JavaScript and TypeScript versions.

Read all about the app here.

CDN

Phaser is on jsDelivr which is a "super-fast CDN for developers". Include the following in your html:

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

or the minified version:

<script src="//cdn.jsdelivr.net/npm/[email protected]/dist/phaser.min.js"></script>

API Documentation

Go to https://newdocs.phaser.io/ to read the docs online. Use the links to navigate the namespaces, classes and Game Objects lists and also use the search box.

The documentation for Phaser is an on-going project. Please help us by contributing improved docs and examples.

TypeScript Definitions

The TypeScript definitions can be found inside the types folder. They are also referenced in the types entry in package.json.

Depending on your project, you may need to add the following to your tsconfig.json file:

"lib": ["es6", "dom", "dom.iterable", "scripthost"],
"typeRoots": ["./node_modules/phaser/types"],
"types": ["Phaser"]

The TypeScript defs are automatically generated from the JSDoc comments found in the Phaser source code. If you wish to help refine them then you must edit the Phaser JSDoc blocks directly, not the defs file. You can find more details about the parser we built in the scripts/tsgen folder.

License

Phaser is released under the MIT License.

Getting Started

Tutorials and guides on Phaser are being published every week.

Free Phaser by Example Book

A brand-new free 500 page book on game development with Phaser. Learn by building shoot-em-ups, puzzle games, rogue-likes and more.

Phaser by Example

Written by long-time prolific Phaser enthusiast Pello Xabier Altadill and Richard Davey, creator of Phaser, it contains over 500 pages of brand-new, up-to-date content on building games with Phaser v3.80.

The book is divided into 17 chapters and takes you through the process of creating a variety of different games. As the title implies, this allows you to learn by working through real-life examples. The games start off simple with an infinite runner game - but then progress through how to build a shoot-em-up, a platformer, a puzzle game, a rogue-like, a story game, and even includes a 3D game and a Multiplayer shooter.

As well as the games, Richard has written a large section on the core concepts of Phaser, covering the terminology and conventions used by the framework, as well as a comprehensive deep dive into Game Objects - the life blood of any Phaser game. You'll be guided through topics including the Game Object Factory, Masks, custom Blend Modes, and lots more.

The book is then rounded out with chapters on working with assets, popular build tools, the rule of 4:44, and the benefits of taking part in game jams β€” as well as a handy Phaser cookbook.

Download the book by registering for a free Phaser account.

Source Code Examples

During the development of Phaser, we created hundreds of examples with the full source code and assets ready available. These examples can be browsed on the Phaser 3 Labs, or clone the examples repo. We are constantly adding to and refining these examples.

Hathora

Hathora Cloud is a scalable hosting platform for online multiplayer games. You upload your server project using the Hathora console or CLI, and then dynamically create server instances in 10+ regions around the world. You get charged only for the duration of active matches/sessions. It's perfect for nodejs servers handling WebSocket connections, and takes care of SSL termination (for wss) and DDoS protection.

They have also published a brand-new tutorial on creating a scalable multiplayer Phaser game. If you think this could be useful for your hosting needs, join their Discord server to get in touch.

Huge list of Phaser 3 Plugins

Super community member RexRainbow has been publishing Phaser 3 content for years, building up an impressive catalogue in that time. You'll find loads of plugins, from UI controls such as text input boxes, to Firebase support, Finite State Machines and lots more. As well as the plugins there is also a comprehensive set of 'Notes' about Phaser 3, going into great detail about how the various systems work. It's an invaluable resource and well worth checking out at https://rexrainbow.github.io

Create Your First Phaser 3 Example

Phaser Sandbox: If you'd rather not test Phaser locally, then you can register for a free account on our site and use the Phaser Sandbox. Here you'll find a fully-configured online editor, ready to go. Otherwise, read on ...

Create an index.html page locally and paste the following code into it:

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser-arcade-physics.min.js"></script> 
</head>
<body>

    <script></script>

</body>
</html>

This is a standard empty webpage. You'll notice there's a script tag that is pulling in a build of Phaser 3, but otherwise this webpage doesn't do anything yet. Now let's set-up the game config. Paste the following between the <script></script> tags:

const config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 }
        }
    },
    scene: Example
};

const game = new Phaser.Game(config);

config is a pretty standard Phaser 3 Game Configuration object. We tell config to use the WebGL renderer if it can, set the canvas to a size of 800 x 600 pixels, enable Arcade Physics, and finally we tell it to use the Example Scene. This hasn't been implemented yet, so if you run this JavaScript code now you will have an error. Add the following above the config:

class Example extends Phaser.Scene
{
    constructor ()
    {
        super();
    }

    preload ()
    {
        this.load.setBaseURL('https://labs.phaser.io');

        this.load.image('sky', 'assets/skies/space3.png');
        this.load.image('logo', 'assets/sprites/phaser3-logo.png');
        this.load.image('red', 'assets/particles/red.png');
    }

    create ()
    {
    }
}

Here we create a Scene called Example. We've given it 2 functions. The preload function is where you load assets into your game. In preload, we set the Base URL to be the Phaser server and load 3 PNG files.

The create function is empty, so it's time to fill it in:

create ()
{
    this.add.image(400, 300, 'sky');

    const particles = this.add.particles(0, 0, 'red', {
        speed: 100,
        scale: { start: 1, end: 0 },
        blendMode: 'ADD'
    });

    const logo = this.physics.add.image(400, 100, 'logo');

    logo.setVelocity(100, 200);
    logo.setBounce(1, 1);
    logo.setCollideWorldBounds(true);

    particles.startFollow(logo);
}

Here we add a sky image into the game and create a Particle Emitter. The scale value means that the particles will initially be large and will shrink to nothing as their lifespan progresses.

After creating the emitter, we add a logo image called logo. Since logo is a Physics Image, logo is given a physics body by default. We set some properties for logo: velocity, bounce (or restitution), and collision with the world bounds. These properties will make our logo bounce around the screen. Finally, we tell the particle emitter to follow the logo - so as the logo moves, the particles will flow from it.

Run it in your browser and you'll see the following:

Phaser 3 Demo

If you can't get it to run, then have a look at this example in the Phaser Sandbox.

This is a tiny example, and there are hundreds more for you to explore, but hopefully it shows how expressive and quick Phaser is to use. With just a few easily readable lines of code, we've got something pretty impressive up on screen!

Building Phaser

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

Phaser Compressor

Use our powerful new web-based tool to crunch your Phaser bundles down by up to 60%, enabling only the features your game requires.

Read more about Phaser Compressor

Building from Source

If you wish to build Phaser from source, ensure you have the required packages by cloning the repository and then running npm install on your source directory.

You can then run webpack to create a development build in the build folder which includes source maps for local testing. You can also npm run dist to create a minified packaged build in the dist folder. For a list of all commands available use npm run help.

Change Log

Change Log

Due to the increasing size of our Change Logs we have now split them up, one version per folder.

We've organized the Change Logs into commonly themed sections to make it more digestible, but we appreciate there is a lot in there. Please don't feel overwhelmed! If you need clarification about something, join us on the Phaser Discord and ask.

Contributing

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

  • Found a bug? Report it on GitHub Issues and include a code sample. Please state which version of Phaser you are using! This is vitally important.

  • Before submitting a Pull Request run your code through ES Lint using our config and respect our Editor Config.

  • Before contributing read the code of conduct.

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

Created by

Phaser is a Photon Storm and Phaser Studio Inc production.

storm

Created by Richard Davey and the team at Phaser Studio Inc. Powered by coffee, anime, pixels and love.

The Phaser logo and characters are Β© 2011 - 2024 Phaser Studio Inc.

All rights reserved.

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

phaser's People

Contributors

alvaroestradadev avatar alvinsight avatar alxwest avatar benjamindrichards avatar bitnenfer avatar clark-stevenson avatar d-parkinson1 avatar englercj avatar georgiee avatar hexus avatar jasonhk avatar jcyuan avatar jorbascrumps avatar jsoref avatar mikewesthad avatar orblazer avatar pavle-goloskokovic avatar photonstorm avatar pixelpicosean avatar pjbaron avatar pnstickne avatar rblopes avatar rexrainbow avatar rgk avatar samme avatar svipal avatar tadejzupancic avatar vbornand avatar vforsh avatar zekeatchan 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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's Issues

Particle position incorrect for first rendered frame when camera is panned away from world origin

Particles emitted while the camera is panned away from the world origin, and where the emitter would be outside the visible area if the camera were at world origin, are displayed for their first frame in an incorrect location. After the first rendered frame of the particle's existance, the position is correct, resulting in a brief flash in the incorrect position.

This appears to be because of the following in the reset function setting sprite.position.x/y, which I believe are the display coordinates, to be the passed world coordinates:

Phaser.Sprite.prototype.reset = function(x, y) {
    this.x = x;
    this.y = y;
    this.position.x = x;
    this.position.y = y;

Upon replacing:

    this.position.x = x;
    this.position.y = y;

with:

    this.position.x = this.x - (this.game.world.camera.x * this.scrollFactor.x);
    this.position.y = this.y - (this.game.world.camera.y * this.scrollFactor.y);

the behavior ceases to occur.

While I assume that this issue can occur with any other sprite, I've been unable to replicate it outside of the particle emitter.

Group does not have x,y position

In Flixel you could set a group's x,y position. In Phaser Group extends Basic which doesn't have x,y position.

Not sure if group needs things but it would be a nice to have especially when you want to bulk move a group of Sprites into place at the start of a level.

Sprite.animations.play() plays always the last animation added

No matter which animation_id you use in Animation.play() method, it will always play the last animation added.

Suppose this code:

  player.animations.add('idle', ['idle_0.png'] , 1, false, false);
  player.animations.add('run', ['run_0.png', 'run_1.png', 'run_2.png'], 1, true, false);
  player.animations.add('jump', ['jump_0.png', 'jump_1.png', 'jump_2.png'], 1, true, false);

  player.animations.play('idle');

Despite the fact I choose the 'idle' animation to be played actually the 'jump' animation will be played, no matter which animation_id I choose.

Looking at the code Phaser.Animation#L61 I found:

  this._frames = frames;

The value of "frames" variable is the pointer of "this._outputFrames", not its value.

It means the next time Animation.add() method is invoked the attribute this._outputFrames will be updated with a new set of frames AnimationManager.js#L129 :

  this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);

Therefore the attribute "_frames" from all animations will point to the last animation added, because all _frames variables points to this._outputFrames attribue.

My suggestion to fix this problem could be make those changes at AnimationManager.js#L127:

  var outputFrames = [];
  this._frameData.getFrameIndexes(frames, useNumericIndex, outputFrames);

  this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, outputFrames, frameRate, loop);

  // If this._outputFrames is used in another place, then you could do this
  this._outputFrames = outputFrames;

Event for while dragging

There is an event for when drag has started, and one for when drag has ended - however there is no accompanying event for while an object is being dragged.

For example I need to update some information while an object is being dragged, but I have no way of knowing when that is occurring without polling each frame. This is fine, except if you have many objects, now you have to wire up that booking, and it seems like a simple signal would side step those problems

Animation Throw Error on missing frame data

When setting up texture atlas animation by framename (and possibly any animation) if you request a frame that doesn't exist it defaults to frame 0. Example:

player.animations.add('idle', ['player-fire-' + weaponId + '-00.png', 'player-fire-' + weaponId + '-01.png'], 10, true, false);

In the above example I don't have the last frame in the atlas so the entire animation breaks and only displays whatever is the first frame in the atlas.

The solution would be to have the animation class throw an error if the frame is not found when adding or animating.

Need game.add() helper method

Flixel had a helper method called add() which quickly allowed you to add sprites to the world without having to talk to the world directly. Currently there are a bunch of create helper methods but no simple way to add something created manually such as custom sprites.

Click to resume game after loosing focus

I am running into an issue where a chrome plugin is breaking the ability for Phaser to detect when the focus returns to the game. While I have been able to isolate the issue to a specific plugin one way to resolve this would be to simply add the ability to click back inside of a game to reactivate it once it is paused.

Use Typescript arrow notation

Found in some parts of your code:

var that = this;
image.onload = function () {
that.context.drawImage(image, 32, 32);
};

As you are using Typescript would be better to use arrow notation to preserve context:

image.onload =()=> {
this.context.drawImage(image, 32, 32);
};

Anyway awesome project!!

Multiple calls to animation.play

If you continuously call sprite.animation.play(...) it will not play the animation. The play method of AnimationManager needs a guard clause:

public play(name: string, frameRate?: number = null, loop?: bool) {

            if (this.currentAnim == this._anims[name])
                return;

            if (this._anims[name])
            {
                this.currentAnim = this._anims[name];
                this.currentAnim.play(frameRate, loop);
            }

        }

Here is an example of the use case:

function update(){
// Player animations
        if (Math.abs(player.velocity.x) > 10) {
            player.animations.play('walk');
        }
        else{
            player.animations.play('idle');
        }
}

This way I can continuously call the correct animation based on a Sprite's velocity for example but the animation shouldn't get interrupted.

Safari issue, Phaser demos not working

Hi
Just to let you know that on my freshly installed Safari for snow leopard (5.1.9), with javascript enabled, all out of the box, etc, Phaser's demo don't work
For instance, when I go here:
"http://gametest.mobi/phaser/index.php?f=follow%20sprite.js&d=cameras"

All I get is the blue background screen, the 3 buttons at the top "Home", "View JavaScript", "view TypeScript" and
"You'll learn best from these Tests by viewing the source code
Use the arrow keys / mouse to move around most of them.
Phaser"
At the bottom of the page

I'm using Mac OSX 10.6.8

Since I'm new to github I don't know if this issue was already reported, I've googled and found nothing

AMD support

Would be helpful for those of us not using TypeScript.

loadGraphic doesn't clear previous settings

So this is a poor setup on my part but it exposed this issue. Basically if you have a base class that sets up a bunch of animations and have another class that extends it then attempts to change its graphics by calling loadGraphic it will not correctly clear the previous reference to the base class's animation image. Here is the example:

// Class 1
constructor(...) {
     super(...);
     this.animations.add("test", [1, 2, 3], 3, true);
     this.animations.play("test");
}

// Class 2
constructor(...) {
     super(...);
     this.loadGraphic("newGraphic"); // <- this is a new size image but with same # of frames
     this.animations.play("test"); // <- should use newGaphic but shows graphic setup in base class
}

Ideally any call to loadGraphic should clear out the previous set of animations or, retain the previously set up animations in the child class but link to the proper sprite/texture image (which would be more ideal in this particular use case). I am using this for two classes that basically have the same exact animations but each one has different base values defined in the class. So technically you should be able to swap out the sprite on the fly and still retain all the animation setup.

Hope that makes sense?

Font Class

Been talk to you about this for a while but wanted to get it on the to do list. We need a Texture Atlas based font class. Ideally it would extend Basic and allow you to add to the world just like a Sprite so it's part of the render loop. Also I'd like to have some way of having it cache the text so when you set text on it, that gets rendered to an off screen canvas so when it draws to the display it's not rendering each character individually. This should be optional since it would be expensive for something that gets updated frequently.

I have been working on my own version and will try to clean it up and attach to the issue if you don't get to it first.

Missing direction constants

In Flixel there were direction constants for up, right, down, left, floor and ceiling. I noticed .facing still exists but there is no addition logic to support this which was helpful in Flixel. Can these constants bee added in Phaser or should they stay out and consider deprecating facing?

Sprite flickers default texture atlas frame 0 on creation

I am noticing a strange issue where I see the default frame of a texture atlas before an animation starts playing. In my case I'll see a "bag" graphic (which is my frame 0 in the atlas) and then I'll see the correct zombie animations. After that initial flicker everything is fine. The way I get around this is by setting the sprite.animation.frameName to the first frame of my "walk" animation before adding and playing the animation:

zombie.animations.frameName = "zombie-a-" + style + "-00.png";
zombie.animations.add('walk', ['zombie-a-' + style + '-00.png', 'zombie-a-' + style + '-01.png', 'zombie-a-' + style + '-02.png', 'zombie-a-' + style + '-03.png', 'zombie-a-' + style + '-04.png', 'zombie-a-' + style + '-05.png'], 10, true, false);
zombie.animations.play("walk");

This most likely has to do with the fact that you automatically default the animation to frame 0 which makes sense if you forget to set a graphic for a Sprite but when you are stringing together something more complex it is a problem since you have to manually clear that default image before it renders to the display.

Possible solution:
When you add an animation, assuming no other animations have been added, that should become the default animation. It's first frame should be set so that when it displays for the first time you see the correct animation frame.

Phaser.Utils.Debug - renderSpriteBounds() - Cannot read property 'x' of undefined

renderSpriteBounds: function (sprite, color) {

    if (this.context == null)
    {
        return;
    }

    color = color || 'rgba(0, 255, 0, 0.2)';

    this.start();
    this.context.fillStyle = color;
    this.context.fillRect(sprite.worldView.x, sprite.worldView.y, sprite.worldView.width, sprite.worldView.height);
    this.stop();

}

The fix:
this.context.fillRect(sprite.x, sprite.y, sprite.width, sprite.height);

The proposal:
color = color || 'rgba(0, 255, 0, 0.5)';

Because 0.2 was way to hard to be detect :P

Game.camera is set in World but it is read only

In World.ts line 21 is this._game.camera = this.cameras.current; so all games break on this line since in Game.ts line 445 there's a get method but no public set. Commenting out that line in World.ts seems to work but I haven't tested it much.

Recursively entering StateManager.start

If a state contains a preloader that does not load anything and has a create() function that calls start() to another state, the create() function of the new state will be called twice. To repro, comment out the load() calls in Preloader class of the wip/examples/state example; MainMenu.create() should show up twice.

A convoluted situation, but it's a dormant bug that may show up in other, more normal circumstances.

Map Collision issue in 0.9.5

Hi.

I finally got around to checking the fix for my previous map collision issue. (#18) The fix works great thanks. But now I have a different issue.

A sprite collision with a map tile is being allowed to "passthru" the tile even though stop sprite is set to true.

map.setCollisionByIndex([51,52,53,61,62,63,71,72,73,74,81,101,102,111,112], Phaser.Collision.ANY, true, true, true);

However, this is only happening from 1 side of the tile(s) and if you persist in colliding on that single side. The other 3 sides of the tile(s), block the sprite properly. This means if you are controlling the sprite with an arrow key and keep pressing the key to keep the sprite moving even after you've collided with the tile. (e.g. not change the direction of movement)

I am not sure if this is related, but the sprite that is colliding into the map tile, is rotated 90 degrees and that is the orientation that is allowed to passthru. The other rotation angles are properly stopped on collision.

Thanks for both your help and providing us with your great engine.

Arnie Forte

Race Condition on init()

var myGame = new Phaser.Game(this, 'game', 800, 600, init, create, update);
console.log("done")

function init(){
    console.log("and initialized")
    myGame; // may not be initialized
}

produces

$ and initialized
$ done

Especially if files are loaded async or via requirejs.

Creating new arrays instead of clearing old ones

Hi,

There are lots of garbage collections going on even when nothing happens on screen. I analyzed it and it seems that one of the reasons for the GC is because in several places in the code arrays are cleared by creating new arrays:

PIXI.texturesToUpdate = [];

The proper way to clear an array is to set its length to 0

PIXI.texturesToUpdate.length = 0;

Would you like me to fix this and submit a pull request?

frameIndex and frame not in sync

When testing animations.frame and animations.currentFrame.index the two properties don't return the same value. I am expecting animations.frame to return the current frame number of an animation similar to how Flixel worked.

Here is an example:

//create
this.animations.add("hide", [1, 2, 3], 1, false);
this.animations.play("hide");

//update
console.log("frame", this.animations.frame, this.animations.currentFrame.index);

Right now animation.frame will continue to return 0 even when currentFrame returns 3 which is the correct frame at the end of the animation.

Map/sprite Collision Callback is not firing

Hello,

I have been working with the latest Phaser build 0.9.4 and have configured a map. Collision with the map works but when I try to add a callback to the map.collide() call, it does not fire.

Here is my code snippet of what I am trying to accomplish, which is destroy a particular sprite when it collides with an obstacle in the map.

function bulletCollides(targetA) {
console.log("bullet crash");
recycleBullet(targetA);
}
.
.
.
function recycleBullet(bullet) {
if(bullet.exists && bullet.x < -40 || bullet.x > 1640 || bullet.y < -40 || bullet.y > 840) {
bullet.exists = false;
}
}
.
.
function create() {
.
.
map = myGame.createTilemap('jsontiles', 'jsontest', Phaser.Tilemap.FORMAT_TILED_JSON);
map.setCollisionRange(51, 53);
map.setCollisionRange(61, 63);
map.setCollisionRange(71, 73);
.
bullets = myGame.createGroup(50);
// P.S. Bullets are TextureAtlas Animations.
for(var i = 0; i < 50; i++) {
.
.
tempBullet.animations.add('fire_ball', [
'fireball01_01.png',
.
.
],9,true,false);
bullet.add(tempBullet);
}
.
.
.
}

function update() {
.
.
.
map.collide(r_dragon); // Player Collision with map obstacle
map.collide(bullets, bulletCollides); // Player's bullet crashes with map obstacle
}

As you can see I pretty much combined code from the examples. I am not sure if I am missing something.

Thanks,
Arnie Forte

Parent element for canvas is ignored?

I'm trying to create a game canvas within a specific container element. So I've got:

var game = new Phaser.Game(width, height, Phaser.AUTO, container,
{preload: preload, create: create, update: update}, true);

But the canvas element is not created inside the 'container' element - it's just appended to the end of the DOM.

What am I doing wrong?

Thanks!

Sprite.{x,y} vs Sprite.position.{x,y} What should I use?

Hi Richard!

Suppose the following code:

function update() {
    // game's world size = 800 x 600
    // At the begining sprite is located at (400,300)
    if ( player.position.x < -player.width ) {
      player.position.x = game.width
    } 

    if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
      if ( 0 == player.velocity.x ) {
        player.velocity.x = -200;
        player.animations.play('walk');
      }
    }
  }

It simply moves the sprite to the left side, and when it reaches the border it will appear on the right side then. Unfortunatelly this won't happen until I change player.position.x by player.x:

function update() {
    // game's world size = 800 x 600
    // At the begining sprite is located at (400,300)
    if ( player.x < -player.width ) {
      player.x = game.width
    }
   ...
  }

So my question is, what is the correct attribute I should use? Sprite.{x, y} or Sprite.position.{x,y}?

Thanks!

renderPoint() in GeomSprite.ts looks a bit off to me.

Hi, I could be completely wrong about this (I don't really know JavaScript or TypeScript...), but I think the renderPoint() function starting on line 333 in GeomSprite.ts currently looks like it'll ignore the offset and size parameters passed to it.

public renderPoint(offsetX, offsetY, point, size) {

    offsetX = 0;
    offsetY = 0;
    this._game.stage.context.fillRect(offsetX + point.x, offsetY + point.y, 1, 1);

}

Looking at it's signature I'm guessing it was probably intended to go something like this with the offsets and size being optional:

public renderPoint(offsetX?: number = 0, offsetY?: number = 0, point: Point, size?: number = 1) {

    this._game.stage.context.fillRect(offsetX + point.x, offsetY + point.y, size, size);

}

Though I'd move the point over to be the 1st parameter like this:

public renderPoint(point: Point, offsetX?: number = 0, offsetY?: number = 0, size?: number = 1) {

    this._game.stage.context.fillRect(offsetX + point.x, offsetY + point.y, size, size);

}

No destroy method on State class

There should be a destroy method you can override in order to better organize state tear down when moving from state to state. Also the Game class will need to automatically call this when switching to the next state.

Can't set Sprite's color via makeGraphic

Color param supplied to sprite.makeGraphic does not correctly set a color on a sprite without an image. You can pass in a number but it is not saved in the makeGraphic method:

line 93:

public makeGraphic(width: number, height: number, color: number = 0xffffffff): Sprite {

            this._texture = null;
            this.width = width;
            this.height = height;

            this._dynamicTexture = false;

            return this;
}

And since the color param is not being saved it appears to be hard coded to the render code on line 288:

this._game.stage.context.fillStyle = 'rgb(255,000,255)';

Suggested solution: supply a rgb string in makeGraphic or accept a color and convert it to rbg before storing it to a variable on the sprite instance to be used in the render logic.

Volume ignored first time sound is played

The first time I call:
myGame.sound.play('gameOver', 0.1, false);

the volume is ignored and is played at volume=1. Subsequent times it is played, the volume param works.

Pause/resume music on game pause

Music will pause when the game pauses, but it will not resume upon unpausing the game.

game.onPause.add(function () {
music.pause();
});
game.onResume.add(function () {
music.resume();
});

Game.ts does not reference State.ts & switchState is not types to State class

Normally I reference Game.ts in my classes to "include" most of the core library and started realizing that Game.ts does not have a reference to State.ts. Also, switching between states should be typed to a State class to avoid issues with passing in the wrong type of Class:

public switchState(state, clearWorld: bool = true, clearCache: bool = false) {

Here it doesn't have a type. I would actually suggest using an Interface at the very least.

Consistent API around referencing the game instance

There are 2 inconsistent ways to get reference to the game instance depending on what class you are in. Game Objects have a private variable _game while states have game. This should be the same throughout the Framework. I suggest using a game getter/setter to clean things up in the Basic class

Plus this is a TS issue since technically you shouldn't be able to access private vars when extending a class so it would be best to shy developers away from directly accessing anything with an underscore.

[website] Clicking the links under "features" jumps the site to the top.

When you mouse over the features like "input" it shows the details in the game window, but if you inadvertently click that "input" text it jumps you back to the top of the page because you are linking to "#" you need to add some preventDefault js or change those anchors to something else...

Game.camera not updated by Game.prototype.switchState()

When Game.prototype.switchState() is called, it calls CameraManager.prototype.destroy() which creates and assigns a new camera to its current instance variable, but the camera instance variable in the Game instance is not updated.

Wouldn't it make sense to use a getter instead of an camera instance variable for the Game class, like this:

public get camera(): Camera {
  return this.world._cameras.current;
}

That way you do not have to keep it in sync manually.

The code that helped detect the problem:

    Phaser.Game.prototype.transitionToState = function(state, color, duration, completeCallback) {
        if (color == null) {
            color = 0x000000;
        }
        if (duration == null) {
            duration = 0.6;
        }

        var _this = this;

        var debugCameras = function(msg) {
            var id1 = _this.camera;
            id1 = id1 && id1.ID;
            var id2 = _this.world;
            id2 = id2 && id2._cameras;
            id2 = id2 && id2.current;
            id2 = id2 && id2.ID;

            console.log('--- ', msg, ' ---');
            console.log(_this.time && _this.time.now);
            console.log('Game#camera.ID: ', id1);
            console.log('Game#world._cameras.current.ID: ', id2);
        };

        var onFadeCompleted = function() {
            debugCameras('Before switchState');
            _this.switchState(state);
            debugCameras('Before flash');
            _this.camera.flash(color, duration / 2, onFlashCompleted);
        };

        var onFlashCompleted = function() {
            debugCameras('After transition');
            completeCallback();
        };

        if (_this.camera) {
            debugCameras('Before fade');
            _this.camera.fade(color, duration / 2, onFadeCompleted);
        } else {
            onFadeCompleted();
        }
    };

That code above behaves differently depending on when and how often it is called. But the third and all following calls to the function print out the "Before fade" message and then do nothing at all, since the fade is called on the wrong Camera instance.

Group does not pass reference of game to newly recycled objects

If you use recycle to create an object when the group is empty it will not correctly supply the passed in ObjectClass a reference to game. I have modified this in my own build to do:

return this.add(new ObjectClass(this._game));

on lines 289 and 317. Since the ObjectClass parameter is not typed nor is the return I am just making the assumption that the simplest primitive a Group can accept is Basic. Is there a use case where you would use group to manage other objects that are not extended from basic?

Here is my use case:

function creatBullet() {
        var bullet:Phaser.Sprite = <Phaser.Sprite>bulletGroup.recycle(Phaser.Sprite);
        bullet.x = player.x + (player.flipped ? 0 : player.width);
        bullet.y = player.y + 25;
        bullet.loadGraphic("entities");
        bullet.flipped = player.flipped;
        bullet.animations.frameName = "bullet-gun.png";
}

You should probably add some more tests for groups.

ArcadePhysics collision bug - separateY function, and wrong _bounds2.heigh

Collision bug when manual reposition object with "x/y" coordinate.

Please see the console.log of this modified example:

http://mihail.ilinov.eu/games/phaser/examples/quadtree/quadtree2-BUG.php

I've added some console.logs and debugger in ArcadePhysics.js when the "abnormal" collision occurred.

Then you can see that before:

        //  Check if the Y hulls actually overlap
        this._bounds1.setTo(body1.x, body1.y - ((body1.deltaY() > 0) ? body1.deltaY() : 0), body1.width, body1.height + body1.deltaAbsY());
        this._bounds2.setTo(body2.x, body2.y - ((body2.deltaY() > 0) ? body2.deltaY() : 0), body2.width, body2.height + body2.deltaAbsY());

Π’he _bounds2.height is ok 16px, and after that when the object.x and object.y is changed than _bounds2.height goes to 314.4999999998763 which is wrong value for shure...

Create Factory for Game & Class

I'd like to propose removing the tightly coupled create methods you have on Game and State for groups, sprites, particles, etc and add them into a Create Factory class. Ideally you would get a reference to create in the game instance like so:

game.create

examples:

game.create.createCamera()
game.create.createSprite()
game.create.createGroup()

which would contain the same helper methods you already have. All this factory would need is a reference to game. Once this is in place, the State class can simply use the same game.create instance allowing developers to extend the create factory with their own class and add additional functionality to it that will work throughout the game engine.

This would also allow you to decouple the hard coded methods and project the engine from future updates down the line in case you add new primitive elements to the game.

Can't access Stage canvas

In the Stage constructor we need something like added

this.canvas.id = "game-canvas"

or let us pass in a reference to the canvas element to be used. This is important for specifically styling the canvas element, in my case I want to add some custom re-size logic for Windows 8 but I don't have an easy way to access the canvas tag used by stage.

addImageFile fails silently

Hi,

I am just starting with Phaser. I call loader.addImageFile with a presumably incorrect path but it fails silently (no error message in the console). It took me some time to figure that this is the problem. I am using the build product directly (not bringing the entire repo).
Is there some sort of a "Debug" flag I need to turn on to get errors when something fails?

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.