Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
7. January 2015

 

It’s most a maintenance release, so the list of new features is fairly sparse:

 


New Features
  • Phaser.Loader now supports BLOB urls for audio files (thanks @aressler38 #1462)
  • Line.reflect will calculate the reflected, or outgoing angle of two lines. This can be used for Body vs. Line collision responses and rebounds.
  • Line.normalAngle gets the angle of the line normal in radians.
  • Line.normalX and Line.normalY contain the x and y components of the left-hand normal of the line.
  • Line.fromAngle will sets this line to start at the given x and y coordinates and for the segment to extend at angle for the given length.
  • BitmapData.drawGroup draws the immediate children of a Phaser.Group to a BitmapData. Children are only drawn if they have their exists property set to true. The children will be drawn at their x and y world space coordinates. When drawing it will take into account the child's rotation, scale and alpha values. No iteration takes place. Groups nested inside other Groups will not be iterated through.

 

You can read the complete release notes here.

 

The release 2.3 milestones are available here.

 

They also made this announcement regarding version 3:

We're hard at work on Phaser 3. Development on the brand new renderer began in earnest last year and we're already seeing exceptional results from it. You can follow our development in the forum and public repo. Even though we're working on taking Phaser 3 into ES6 and the next generation of web browsers, we haven't stopped with the 2.x branch.

 

If Phaser sounds interesting to you, of course, Gamefromscratch has an extensive tutorial series available here.

Programming News


4. December 2014

 

The Phaser HTML5 game development library has been churning out the releases as of late, and just yesterday 2.2.1 was released.  Perhaps most impressively, much of the releases content came from members within the community, always a good sign with open source projects. 

 

The biggest new feature is the Scale Manager, which you can read about here or from this newly released e-book.  The ScaleManager is to help enable your code to run on devices with multiple different resolutions.  The biggest change is Phaser moved to a proper fixed-step game loop, fully decoupling logic and rendering.

 

The full (and massive) change log below:

 

New Features
  • Updated to Pixi v2.2.0 - see separate change log entry below.
  • Cache.getRenderTexture will retrieve a RenderTexture that is stored in the Phaser Cache. This method replaces Cache.getTexture which is now deprecated.
  • Cache.autoResolveURL is a new boolean (default false) that automatically builds a cached map of all loaded assets vs. their absolute URLs, for use with Cache.getURL and Cache.checkURL. Note that in 2.1.3 and earlier this was enabled by default, but has since been moved behind this property which needs to be set to true before you load any assets to enable.
  • You can now call Tween.to again on a Tween that has already completed. This will re-use the same tween, on the original object, without having to recreate the Tween again. This allows a single tween instance to be re-used multiple times, providing they are linked to the same object (thanks InsaneHero)
  • Phaser.Color.valueToColor converts a value: a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components (thanks @pnstickne #1264)
  • Stage.backgroundColor now supports CSS 'rgba' values, as well as hex strings and hex numbers (thanks @pnstickne #1234)
  • Pointer.addClickTrampoline now adds in support for click trampolines. These raise pointer events into click events, which are required internally for a few edge cases like IE11 full screen mode support, but are also useful if you know you specifically need a DOM click event from a pointer (thanks @pnstickne #1282)
  • Point.floor will Math.floor both the x and y values of the Point.
  • Point.ceil will Math.ceil both the x and y values of the Point.
  • ScaleManager.scaleSprite takes a Sprite or Image object and scales it to fit the given dimensions. Scaling happens proportionally without distortion to the sprites texture. The letterBox parameter controls if scaling will produce a letter-box effect or zoom the sprite until it fills the given values.
  • Phaser.DOM.getBounds is a cross-browser element.getBoundingClientRect method with optional cushion.
  • Phaser.DOM.calibrate is a private method that calibrates element coordinates for viewport checks.
  • Phaser.DOM.aspect gets the viewport aspect ratio (or the aspect ratio of an object or element)
  • Phaser.DOM.inViewport tests if the given DOM element is within the viewport, with an optional cushion parameter that allows you to specify a distance.
  • Phaser.DOM.viewportWidth returns the viewport width in pixels.
  • Phaser.DOM.viewportHeight returns the viewport height in pixels.
  • Phaser.DOM.documentWidth returns the document width in pixels.
  • Phaser.DOM.documentHeight returns the document height in pixels.
  • TilemapLayers have been given a decent performance boost on canvas with map shifting edge-redraw (thanks @pnstickne #1250)
  • A large refactor to how the internal game timers and physics calculations has been made. We've now swapped to using a fixed time step internally across Phaser, instead of the variable one we had before that caused glitchse on low-fps systems. Thanks to pjbaron for his help with all of these related changes.
  • We have separated the logic and render updates to permit slow motion and time slicing effects. We've fixed time calling to fix physics problems caused by variable time updates (i.e. collisions sometimes missing, objects tunneling, etc)
  • Once per frame calling for rendering and tweening to keep things as smooth as possible
  • Calculates a suggestedFps value (in multiples of 5 fps) based on a 2 second average of actual elapsed time values in the Time.update method. This is recalculated every 2 seconds so it could be used on a level-by-level basis if a game varies dramatically. I.e. if the fps rate consistently drops, you can adjust your game effects accordingly.
  • Game loop now tries to "catch up" frames if it is falling behind by iterating the logic update. This will help if the logic is occasionally causing things to run too slow, or if the renderer occasionally pushes the combined frame time over the FPS time. It's not a band-aid for a game that floods a low powered device however, so you still need to code accordingly. But it should help capture issues such as gc spikes or temporarily overloaded CPUs.
  • It now detects 'spiraling' which happens if a lot of frames are pushed out in succession meaning the CPU can never "catch up". It skips frames instead of trying to catch them up in this case. Note: the time value passed to the logic update functions is always constant regardless of these shenanigans.
  • Signals to the game program if there is a problem which might be fixed by lowering the desiredFps
  • Time.desiredFps is the new desired frame rate for your game.
  • Time.suggestedFps is the suggested frame rate for the game based on system load.
  • Time.slowMotion allows you to push the game into a slow motion mode. The default value is 1.0. 2.0 would be half speed, and so on.
  • Time.timeCap is no longer used and now deprecated. All timing is now handled by the fixed time-step code we've introduced.
  • Time.now can no longer be relied upon to contain a timestamp value. If the browser supports requestAnimationFrame then Time.now will contain the high resolution timer value that rAf generates. Otherwise it will contain the value of Date.now. If you require the actual time value (in milliseconds) then please use Time.timeinstead. Note that all Phaser sub-systems that used to rely on Time.now have been updated, so if you have any code that extends these please be sure to check it.
  • Game.forceSingleUpdate will force just a single logic update, regardless of the delta timer values. You can use this in extremely heavy CPU situations where you know you're about to flood the CPU but don't want Phaser to get stuck in a spiral.
  • Tilemap.createFromTiles will convert all tiles matching the given tile index (or an array of indexes) into Sprites. You can optionally then replace these tiles if you wish. This is perfect for games when you want to turn specific tiles into Sprites for extra control. The Sprites have an optional properties object which they can be populated with.
  • Added support for the Wheel Event, which is the DOM3 spec (thanks @pnstickne #1318)
  • Wheel Scroll Event (old non-FF) and DOM Mouse Wheel (old FF) are supported via a non-exported reused wrapper object; WheelEventProxy. The proxy methods are generated one-time dynamically but only when needed.
  • Key.justDown allows you to test if a Key has just been pressed down or not. You can only call justDown once per key press. It will only return true once, until the Key is released and pressed down again. This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop (thanks @pjbaron #1321)
  • Key.justUp allows you to test if a Key has just been released or not. You can only call justUp once per key press. It will only return true once, until the Key is pressed down and released again. This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop (thanks @pjbaron #1321)
  • Device.whenReady is a new signal that you can use to tell when the device is initialized.
  • Device.onInitialized is dispatched after device initialization occurs but before any of the ready callbacks have been invoked. Local "patching" for a particular device can/should be done in this event.
  • TweenManager.removeFrom method allows you to remove a tween from a game object such as a Sprite (thanks @lewster32 #1279)
  • Tweens have been completely rewritten. They're now much more flexible and efficient than before:
  • When specifying the ease in Tween.to or Tween.from you can now use a string instead of the Function. This makes your code less verbose. For example instead of Phaser.Easing.Sinusoidal.Out and you can now just use the string "Sine".The string names match those used by TweenMax and includes: "Linear", "Quad", "Cubic", "Quart", "Quint", "Sine", "Expo", "Circ", "Elastic", "Back", "Bounce", "Power0", "Power1", "Power2", "Power3" and "Power4". You can append ".easeIn", ".easeOut" and "easeInOut" variants. All are supported for each ease types.
  • Tweens now create a TweenData object. The Tween object itself acts like more of a timeline, managing multiple TweenData objects. You can now call Tween.to and each call will create a new child tween that is added to the timeline, which are played through in sequence.
  • Tweens are now bound to the new Time.desiredFps value and update based on the new Game core loop, rather than being bound to time calculations. This means that tweens are now running with the same update logic as physics and the core loop.
  • Tween.timeScale allows you to scale the duration of a tween (and any child tweens it may have). A value of 1.0 means it should play at the desiredFps rate. A value of 0.5 will run at half the frame rate, 2 at double and so on. You can even tween the timeScale value for interesting effects!
  • Tween.reverse allows you to instantly reverse an active tween. If the Tween has children then it will smoothly reverse through all child tweens as well.
  • Tween.repeatAll allows you to control how many times all child tweens will repeat before firing the Tween.onComplete event. You can set the value to -1 to repeat forever.
  • Tween.loop now controls the looping of all child tweens.
  • Tween.onRepeat is a new signal that is dispatched whenever a Tween repeats. If a Tween has many child tweens its dispatched once the sequence has repeated.
  • Tween.onChildComplete is a new signal that is dispatched whenever any child tweens have completed. If a Tween consists of 4 sections you will get 3 onChildComplete events followed by 1 onComplete event as the final tween finishes.
  • Chained tweens are now more intelligently handled. Because you can easily create child tweens (by simply calling Tween.to multiple times) chained tweens are now used to kick-off longer sequences. You can pass as many Tween objects to Tween.chain as you like as they'll all be played in sequence. As one Tween completes it passes on to the next until the entire chain is finished.
  • Tween.stop has a new complete parameter that if set will still fire the onComplete event and start the next chained tween, if there is one.
  • Tween.delay, Tween.repeat, Tween.yoyo, Tween.easing and Tween.interpolation all have a new index parameter. This allows you to target specific child tweens, or if set to -1 it will update all children at once.
  • Tween.totalDuration reports the total duration of all child tweens in ms.
  • There are new easing aliases:
  • * Phaser.Easing.Power0 = Phaser.Easing.Linear.None
  • * Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out
  • * Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out
  • * Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out
  • * Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out
  • ScaleManager.windowContraints now allows specifying 'visual' or 'layout' as the constraint. Using the 'layout' constraint should prevent a mobile device from trying to resize the game when zooming.

    Including the the new changes the defaults have been changed to

    windowContraints = { right: 'layout', bottom: '' }

    This changes the current scaling behavior as seen in "Game Scaling" (as it will only scale for the right edge) but also prevents such scaling from going bonkers in some mobile environments like the newer Android browser. (Automatic scroll-to-top, albeit configurable, enabled for non-desktop by default is not a fun situation here.)

    To obtain the current semantics on a desktop the bottom should be changed to 'layout'; although this will result in different behavior depending on mobile device. To make the sizing also follow mobile zooming they should be changed to 'visual'.

    Also added temp Rectangle re-used for various internal calculations.

  • Phaser.DOM now also special-cases desktops to align the layout bounds correctly (this may disagree with CSS breakpoints but it aligns the with actual CSS width), without applying a window height/width expansion as required on mobile browsers.

  • Signals have been heavily restructured to cut down on the number that are generated in-game. New signal proxies manage the setting and creation as required, cutting down on the volume of run-time object creation significantly. No user code needs to change, however if you did override Phaser.Signal or Sprite.Events then please be aware of the changes by inspecting the source (and commit #1389 by @pnstickne).
  • Game.lockRender is a new property. If false Phaser will automatically render the display list every update. If truethe render loop will be skipped. You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application. Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
Updates
  • TypeScript definitions fixes and updates (thanks @clark-stevenson @draconisNoctis)
  • The TypeScript definitions have moved to the typescript folder in the root of the repository.
  • Cache._resolveUrl has been renamed to Cache._resolveURL internally and gained a new parameter. This method is a private internal one.
  • Cache.getUrl is deprecated. The same method is now available as Cache.getURL.
  • Loader.useXDomainRequest used to be enabled automatically for IE9 but is now always set to false. Please enable it only if you know your server set-up / CDN requires it, as some most certainly do, but we're finding them to be less and less used these days, so we feel it's safe to now disable this by default (#1248)
  • Game.destroy now destroys either the WebGLRenderer or CanvasRenderer, whichever Pixi was using.
  • Particle.Emitter will now automatically set particle.body.skipQuadTree to true to help with collision speeds within Arcade Physics.
  • Particle.Emitter.explode (or Emitter.start with the explode parameter set to true) will immediately emit the required quantity of particles and not delay until the next frame to do so. This means you can re-use a single emitter across multiple places in your game that require explode-style emissions, just by adjusting the emitter.x andemitter.y properties before calling explode (thanks Insanehero)
  • Phaser.Polygon has been refactored to address some Pixi v2 migration issues (thanks @pnstickne for the original implementation #1267)
  • Polygon.area is now only calculated when the Polygon points list is modified, rather than on every call.
  • Phaser.Polygon can now accept the points list in a variety of formats: Arrays of Points, numbers, objects with public x/y properties or any combination of, or as a parameter list (thanks @pnstickne for the original implementation #1267)
  • All of the Input classes now use the more consistent enabled property instead of disabled. I.e. you can now checkif (input.mouse.enabled) rather than if (!input.mouse.disabled). The disabled property has been moved to a getter for backwards compatibility but is deprecated and will be removed in a future version (thanks @pnstickne #1257)
  • The Input class has been given a minor refactor to tidy things up. Specifically:
    • pointerN are aliases to backed pointers[N-1] array. This simplifies (and increases the efficiency of) looping through all the pointers when applicable; also eliminates pointer-existence checks Removes various hard-coded limits (added MAX_POINTERS); changed maxPointers default
    • Removed some special-casing from cases where it did not matter
    • Removed === false/true, == usage for consistency, changed missing value check to typeof, etc.
    • Updated documentation for specificity; added @public\@protected
    • @deprecated currentPointers due to odd set pattern; totalCurrentPointers is more appropriate. (thanks @pnstickne #1283)
  • Various ScaleManager fixes and updates (thanks @pnstickne):
    • Scale modes can now be set independently
    • Switching between fullscreen and normal correctly restores modes
    • Alignment does not incorrectly offset in fullscreen mode (#1255)
    • Changing scale/alignment promptly refreshes layout
    • isFullScreen returns a boolean, as it should
    • Faster parent checks (if required)
    • NO_SCALE should not not scale (vs previous behavior of having no behavior)
    • Correct usage of scaleMode depending on mode
    • Fullscreen Mode always scaling to fill screen in Firefox (#1256)
  • AudioSprite - removed an unnecessary if-statement (thanks @DaanHaaz #1312)
  • ArcadePhysics.skipQuadTree is now set to true by default. A QuadTree is a wonderful thing if the objects in your game are well spaced out. But in tightly packed games, especially those with tilemaps or single-screen games, they are a considerable performance drain and eat up CPU. We've taken the decision to disable the Arcade Physics QuadTree by default. It's all still in there and can be re-enabled via game.physics.arcade.skipQuadTree = false, but please only do so if you're sure your game benefits from this.
  • Phaser.DOM now houses new DOM functions. Some have been moved over from ScaleManager as appropriate.
  • Key.justPressed has bee renamed to Key.downDuration which is a much clearer name for what the method actually does. See Key.justDown for a nice clean alternative.
  • Key.justReleased has bee renamed to Key.upDuration which is a much clearer name for what the method actually does. See Key.justUp for a nice clean alternative.
  • Keyboard.justPressed has bee renamed to Keyboard.downDuration which is a much clearer name for what the method actually does.
  • Keyboard.justReleased has bee renamed to Keyboard.upDuration which is a much clearer name for what the method actually does.
  • Keyboard.downDuration, Keyboard.upDuration and Keyboard.isDown now all return null if the Key wasn't found in the local keys array.
  • The Phaser.Device class has been made into a singleton and removed it's dependency on Phaser.Game (thanks @pnstickne #1328)
  • ArrayList has been renamed to ArraySet (as it's actually a data set implementation) and moved from the corefolder to the utils folder (thanks @pnstickne)
  • If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out of AudioContext nodes. If this is the case create a global var called PhaserGlobal on the window object before creating the game. The active AudioContext will then be saved towindow.PhaserGlobal.audioContext when the Phaser game is destroyed, and re-used when it starts again (#1233)
  • Camera.screenView is now deprecated. All Camera culling checks are made against Camera.view now instead.
  • Various CocoonJS related hacks removed thanks to fixes from Ludei directly in CocoonJS! Woohoo :)
  • Phaser.HEADLESS check removed from the core game loop. If you need to disable rendering you can now override the Phaser.Game.updateRender method instead with your own.
  • Group.forEach fixed against browser de-optimization (thanks @pnstickne #1357)
  • Phaser.Signals have been taken on a diet. They have been updated such that there is significantly less penalty for having many unused signals. The changes include:
  • * Changing it so there is no dispatch closure created. This is a potentially breaking change for third party code.
  • * In the rare case that code needs to obtain a dispatch-closure, the boundDispatch property can be used to trivially obtain a cached closure.
  • * The properties and default values are moved into the prototype; and the _bindings array creation is deferred. This change, coupled with the removal of the automatic closure, results in a very lightweight ~24bytes/object (in Chrome) for unbound signals.
  • With this change in place Signals now consume less than 50KB / 50KB (shallow / retained memory) for 200 sprites, where-as before they used 300KB / 600KB (thanks @pnstickne #1359)
  • Time.elapsedMS holds the number of milliseconds since the last Game loop, regardless of raF or setTimout being used.
  • Incorrectly prepared tilemap images (with dimensions not evenly divisible by the tile dimensions) would render incorrectly when compared to the display seen in Tiled. The Phaser tilemap code has been adjusted to match the way Tiled deals with this, which should help if you're using tileset images that contain extra padding/margin pixels. Additional console warnings have been added. However the fact remains that you should carefully prepare your tilesets before using them. Crop off extra padding, make sure they are the right dimensions (thanks @SoulBeaver for the report and @pnstickne for the fix #1371)
  • Text.setShadow has had the default color value changed from rgba(0,0,0,0) to rgba(0,0,0,1) so it appears as a black shadow by default - before the alpha channel made it invisible.
  • Math.getRandom will now return null if random selection is missing, or array has no entries (thanks @pnstickne #1395)
  • Array.transposeArray has had a small off-by-one error fixed. It didn't effect the results but meant returned arrays were 1 element bigger than needed (thanks @nextht #1394)
  • State.preRender is now sent two parameters: a reference to the Phaser.Game instance and a new parameter:elapsedTime which is the time elapsed since the last update.
Bug Fixes
  • Tilemaps in WebGL wouldn't update after the first frame due to a subtle change in how Pixi uploads new textures to the GPU.
  • XML files weren't being added to the URL map.
  • Cache._resolveURL was causing a Sound double-load in Firefox and causing errors (thanks @domonyiv #1253)
  • Loader.json was using the wrong context in IE9 with XDomainRequest calls (thanks @pnstickne #1258)
  • Text.updateText was incorrectly increasing the size of the texture each time it was called (thanks @spayton #1261)
  • Polygon.contains now correctly calculates the result (thanks @pnstickne @BurnedToast #1267)
  • Setting Key.enabled = false while it is down did not reset the isDown state (thanks @pnstickne #1190 #1271)
  • The Gamepad.addCallbacks context parameter was never actually remembered, causing the callbacks to run in the wrong context (thanks @englercj #1285)
  • Animation.setFrame used the wrong frames array if useLocalFrameIndex was false and a numeric frame ID was given (thanks @Skeptron #1284)
  • Fullscreen mode in IE11 now works (thanks @pnstickne)
  • Cache.addBitmapData now auto-creates a FrameData (thanks @pnstickne #1294 #1300)
  • P2.BodyDebug circles were drawing at half widths (thanks @enriqueto #1288)
  • FrameData.clone fixed when cloning data using frame names rather than indexes (thanks pjbaron)
  • Lots of the Cache getters (such as Cache.getbitmapData) would return undefined if the asset couldn't be found. They now all consistently return null for missing entries (thanks @Matoking #1305)
  • Phaser games should now work again from the CocoonJS Launcher.
  • Only one of the mouse wheel events is listened to, newest standard first. This fixes a bug in FF where it would use the default DOMMouseWheel (thanks @pnstickne #1313)
  • Stage.smoothed needed to modify the value of PIXI.scaleMode.DEFAULT instead of PIXI.scaleMode.LINEAR (thanks @pixelpicosean #1322)
  • Newly created Groups always had zero z index (thanks @spayton #1291)
  • Sprite.autoCull now properly works if the camera moves around the world.
  • Sprite.inCamera uses a much faster check if auto culling or world bounds checks are enabled and properly adjusts for camera position.
  • Camera.totalInView is a new property that contains the total number of Sprites rendered that have autoCull set to true and are within the Cameras view.
  • Emitter.setScale fixed minX minY order precedence (thanks spayton)
  • Group.iterate can now accept undefined/null as the arguments (thanks @pnstickne #1353 @tasos-ch #1352)
  • When you change State the P2 Physics world is no longer fully cleared. All of the bodies, springs, fixtures, materials and constraints are removed - but config settings such as gravity, restitution, the contact solver, etc are all retained. The P2.World object is only created the very first time you call Physics.startSystem. Every subsequent call hits P2.World.reset instead. This fixes "P2.World gravity broken after switching states" (and other related issues) (#1292 #1289 #1176)
  • Text.lineSpacing works correctly again. Before no space was added between the lines (thanks @intimidate #1367 and @brejep #1366)
  • P2.BodyDebug always lagged behind the position of the Body it was tracking by one frame, which became visible at high speeds. It now syncs its position in the Body.postUpdate which prevents this from happening (thanks @valueerror)
  • A State.preRender callback wasn't removed correctly when switching States.

 

Phaser is available here.

 

Of course, GameFromScratch has a comprehensive Phaser with TypeScript series available here.

News


8. November 2014

 

Amber have just open sourced Copperlicht, a WebGL 3D JavaScript engine.  Copperlich was previously available for 99 Euro per year.

Logo

 

Here is an overview of Copperlicht’s functionality:

  • 3D World editor: CopperLicht comes with a full 3D world editor named CopperCube.
  • Many supported 3D file formats: 3ds, obj, x, lwo, b3d, csm, dae, dmf, oct, irrmesh, ms3d, my3D, mesh, lmts, bsp, md2, stl, ase, ply, dxf, cob, scn and more
  • Built-in Collision detection: Throw a polygon soup into the engine and walk around the 3D world.
  • Lots of 3D graphics features, see below.
  • Incredibly fast: CopperLicht is highly optimized and able to render and animate even huge 3d scenes.
  • Character/Skeletal animation: supports playing back animated meshes with an unlimited amount of joints and an unlimted amount of weights
  • Simple to use: easily understandable SceneGraph API with lots of tutorials and examples in the documentation
  • Binary compilation: Unlike other WebGL 3D Engines, CopperLicht compiles your 3D meshes into a small, binary file which downloads quickly, reducing bandwith usage for your users. Simply import your 3D files into the CopperCube editor and publish it as CopperLicht scene.
  • Totally free: CopperLicht is free to use. And open source. Just download and go!

 

You may notice the strike through that Copperlicht includes a 3D world editor; this isn’t entirely true with the open sourced version.  There is a commercial editor available named CopperCube, however it is a commercial product

 

I have to say, I like this move.  You can create a full game using Copperlicht without the editor, while the editor is available on a 14 day trial.  This means people can contribute to a Copperlicht project without paying money, but there is a value add sell that means the developer can eat!  I hope this will result in an increase in popularity for Copperlicht that in turn increases sales for Coppercube, which would be win/win.  I personally would like to see the demo extended to 30 days, or preferably be 14 actual days, not 14 calendar days.

 

This announcement is quite timely, as I just recently had this conversation on Twitter:

 

TwitterDiscussion

 

I feel almost prescient!

 

This is a slightly different business model, but one I firmly support.  On the whole I think this is a great change.  I have used Irrlicht in the past and was impressed by the engine.  Now I am going to look closer at Copperlight and possibly due a tutorial series on it in the future.  Now that Copperlicht and Coppercube are a bit less intwined, I wonder if Coppercube could move to being more agnostic and be of use to say… Three.js or Turbulenz.

 

Are you at all interested in hearing more about the Copperlicht engine here on GameFromScratch?

News


12. October 2014

 

The following is a guest tutorial written by Guntis at MightyEditor showing how you can easily use MightyEditor and Phaser to create a game.

 

 

This article will give you an example on how to use popular HTML5 game development framework Phaser and editor based on top of it - MightyEditor. This tutorial will take about an hour and only ~90 lines of actual code. Following game development aspects will be introduced: sprites, sprite animations, physics, collision, game states, player death/revival.

 

Requirements

 

You should use the newest version of Google Chrome. Other browsers should work, but are not tested.

 

Creating a project

 

In this tutorial we will create a coin collecting-spike avoiding platformer.

Go to http://mightyeditor.mightyfingers.com/ and click on "Create New Project". Enter the name of your game. In this tutorial, our game will be called "SockMan"

 

1

 

Next, locate the settings panel in the bottom-right and change the worldHeight, worldWidth, viewportHeight, and viewportWidth values to 1026x578, as shown in the image below. Viewport is the size of the in-game camera, but we won't be dealing with camera controls in this tutorial. 

 

2

 

Uploading game assets

 

Next up - game assets. First, download the assets and extract them. Then locate the asset manager in the upper-right corner and either select the Upload File/Upload Folder options or simply drag and drop the files from your file explorer straight to the manager panel.

 

3 

 

Creating the world

 

Select the stamp icon, then, in the asset panel, click on the image you want to place, bg_wall.png, for now and then click on the map grid to  place the asset on the map. Note, that the dark grey area represents the world/viewport. CTRL-click snaps the image to grid and you can move the image around afterwards by selecting the arrow tool in the left side menu. More accurate placement is possible by using the 'settings' menu in bottom-right. Next, place the 'grass_tile.png' asset like described above and you should you get a world like in the picture below.

 

4

 

Next up - grouping the placed objects together. Locate the objects panel in the middle-right and either select Add Group and then select and drag the objects in the newly created group or select the objects and then click on Group Selected Objects (SHIFT-click selects multiple objects). After that, rename the group to "bg" (double-click on group name) and your project should look like the image below.

 

 5

 

Note: it can be useful to lock (small lock icon on the right side) the background and any other groups/objects in place, so they become unclickable and don't mess with placing other objects.

 

Adding foreground objects

 

After placing background, we will add (almost) the rest of the objects to the game world - boxes, grass tiles, chest and spikes. To do that, simply use the stamp tool to place each object on the map (remember about CTRL to snap to grid) and group them accordingly - boxes and grass in "objects", spikes in "spikes" group and leave the chest 'groupless'. Everything should look similar to the image below, but feel free to create your own layout.

 

6

 

As for the actual character and coins, things get a little different, because there are multiple frames per image for animations. Select the character.png asset and in the Settings panel set its frameWidth and frameHeight values to 100px,the anchorX to 0.5 and anchorY values to 0.7.

 

7

After that just place the character sprite on the left side of the map by using the usual stamp tool. Repeat these step with the coin spritesheet, only changing the frameWidth to 113px and frameHeight to 71px. Both anchors are 0.5. Place multiple coins on the map and group them together in a 'coins' group. Finally, select the the text icon (big T) in the toolbar and place a "0" in the top right corner of your game world. In the objects panel, rename it to "gold". Now your game world should look like this and we can turn to actual coding.

 

8 

 

Switching to source editor

 

You can switch to the source editor in the top-left of the screen. Editor keyboard shortcuts can be found here.

 

9

 

Game states

 

Coding is done by using the Phaser development framework (homepage and documentation). There are different states (separate parts of the game like intro, menu, gameplay etc.). The MightyEditor gives you four states by default: boot, load, menu and play, but, in this tutorial, we will only be coding in the play state and without any menus, so we should just go straight to the play state. Switch to the 'menu.js' file and call the switch to the play state.

window.SockMan.state.menu = {
        create: function() {

            this.game.state.start("play");
        },

 

You can now click on the Open Game button in the top panel and the game will load... to a blank screen. The graphics must be initialized beforehand. To do that, we will switch to the play.js state. We need to use the mt.create function in the create method like this:

 

create: function() {
    this.bg = mt.create("bg");
    this.character = mt.create("character");
    this.spikes = mt.create("spikes");
    this.chest = mt.create("chest");
    this.objects = mt.create("objects");
    this.coins = mt.create("coins");
    this.gold = mt.create("gold");
},

 

This initializes and creates the game sprites and sprite groups. Now, when opening the game, the visuals will be there, but the image is static.

 

Adding Physics

 

To add movement, first we must enable physics on the character. To do that, head back to the Map Editor and select your character sprite. In the bottom-right, use the Physics panel to enable it. Set these values:

  • enable: 1
  • immovable: 0
  • size-width: 40
  • size-height: 70
  • gravity-allow: 1
  • gravity-y:1000
  • collideWorldBounds: 1

 

10

 

In the end, everything should look like this:  Note: the size parameters are for the physics body, so the game interacts only with the area you want, not the blank parts or the sprite. Your character should now fall through the floor and stay on the edge of the game (that's what collideWorldBounds is for). To fix that, we must enable collision for the objects group.  To do that, just change the physics enable parameter of the group and add this piece of code in your update method (a function, looped 60 times per second):

 

this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
            console.log('Collision detected');
        }, null, this);

And all should be well. The collision detection's first two arguments check for interaction between two entities - the character sprite and a group of objects - and the third argument is a function which does something when these two objects (the character and a separate object of the group) do collide. Congratulations! Your character no longer falls through the floor tiles (grass/boxes).

 

Movement

 

But we need to move. To do that, the keyboard controls must be enabled beforehand. Simply put these two lines in the create method:

 

this.cursors = this.game.input.keyboard.createCursorKeys();
this.space = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

 

The keyboard.createCursorKeys() method initializes the arrow keys. Other keys, like SPACEBAR, SHIFT or CTRL must be initialized like shown above. After that, define actions to do when a key is pressed in the update method:

 

if (this.cursors.left.isDown) {
    this.character.body.velocity.x = -200;
} else if (this.cursors.right.isDown) {
    this.character.body.velocity.x = 200;
} else {
    this.character.body.velocity.x = 0;
}
if (this.space.isDown || this.cursors.up.isDown) {
    this.character.body.velocity.y = -550;
}

 

Arrow keys control your character, alternatively you can jump with SPACEBAR. Or maybe we should say - fly! But we only want to jump, not fly. To do that, one must enable the character to jump only if it is standing on the ground. Delete the current piece of jump code (the one with space and cursors.up) and instead place this in your collision detection function, so it looks like this:

 

this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
    if (this.space.isDown || this.cursors.up.isDown) {
        if (object.body.touching.up) {
            this.character.body.velocity.y = -550;
        }
    }

}, null, this);

 

Adding Character Animations

 

Animations, just like mostly everything, must first be initialized. In the create method, add these lines of code:

this.character.animations.add('stand', [0, 1, 2, 3], 10, true);
this.character.animations.add('run', [6, 7, 8, 9, 10, 11], 10, true);
this.character.animations.add('jump', [12, 13], 10, false);
this.character.animations.add('die', [18, 19], 10, false);
this.character.animations.play('stand');

 

These lines describe animations for your character. The first argument is the 'key' of the animation, the second - an array of frames which this particular animation uses, the third - frames per second and the last argument describes whether the animation should loop. The last line starts an animation when you launch the game. The rest of the animations is played according to situation, when certain condition is met, like a button press. The rest is added in the update method like this:

 

if (this.cursors.left.isDown) {
    this.character.body.velocity.x = -200;
    this.character.animations.play('run');
    this.character.scale.x = -1;
} else if (this.cursors.right.isDown) {
    this.character.body.velocity.x = 200;
    this.character.animations.play('run');
    this.character.scale.x = 1;
} else {
    this.character.body.velocity.x = 0;
    this.character.animations.play('stand');
}

 

And for jump animation, update your collision detection function with this:

 

this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
    if (this.space.isDown || this.cursors.up.isDown) {
        if (object.body.touching.up) {
            this.character.animations.play('jump');
            this.character.body.velocity.y = -550;
        }

    }
}, null, this);

 

At this point you might be wondering why you can't see a jump animation. It's because it gets overwritten by the 'run' or 'stand' animations since their conditions are met as well. We must invent another variable which tells the animations whether the character is in the air. Long story short, after putting this variable in, all of the update method will look like this:

 

update: function() {
    var standing = false;
    this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
        if (object.body.touching.up) {
            standing = true;
        } else standing = false;
        if (this.space.isDown || this.cursors.up.isDown) {
            if (object.body.touching.up) {
                this.character.animations.play('jump');
                this.character.body.velocity.y = -550;
                standing = false;
            }

        }
    }, null, this);

    if (this.cursors.left.isDown) {
        this.character.body.velocity.x = -200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = -1;
    } else if (this.cursors.right.isDown) {
        this.character.body.velocity.x = 200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = 1;
    } else {
        this.character.body.velocity.x = 0;
        if (standing) this.character.animations.play('stand');
    }
}

 

Collecting Coins

 

Before you are able to collect coins, their physics must be enabled, the physics body size set to 24x24 and offsetY to 10.

 

 

Next, we initialize the animation:

 

this.coins.self.callAll('animations.add', 'animations', 'collect', [7, 8], 10, false);

 

Note the difference between this line and those used to initialize the character's animations. Since the character was a lone sprite but the coins are all in a group, we must use the callAll method which initializes the animation for each and every child of the group separately. The first argument of the method is the method you would normally use, the second is the context and the rest is identical to adding animations as usual. After animating, we determine overlapping between the character and coins, making the coin disappear  when touch ends and the animation is done playing, and adding +1 to the counter in the upper-right corner:

 

this.game.physics.arcade.overlap(this.character, this.coins.self, function(character, coin) {
    coin.body = null;
    var coinCollect = coin.animations.play('collect');
    coinCollect.killOnComplete = true;
    var newPoints = parseInt(this.gold._text) + 1;
    this.gold.setText(newPoints);
}, null, this);

 

The coin.body is set to null, disabling the physics body. Otherwise the points would be added as long as the animation is still playing. since the character overlaps the animation.

 

Spikes, Life and Death

 

Next up is being able to kill the character when it touches the spikes. To do this, you must enable the physics of your 'spikes' group and set the body height to 20px and the offsetY parameter to 44px - this changes the Y coordinate from which the body is calculated. Pretty much an alternative to anchorY. After that comes the now usual collision detection:

 

this.game.physics.arcade.collide(this.character, this.spikes.self, function(character, spike) {
    if (character.alive) character.animations.play('die');
    character.body.velocity.x = 0;
    character.body.velocity.y = 0;
    character.alive = false;
}, null, this); 

 

The only problem now is that, after dying, you can still move. To avoid this, check if the character.alive is true before movement:

 

var standing = false;
this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
    if (object.body.touching.up) {
        standing = true;
    } else standing = false;
    if ((this.space.isDown || this.cursors.up.isDown) && character.alive) {
        if (object.body.touching.up) {
            this.character.animations.play('jump');
            this.character.body.velocity.y = -550;
            standing = false;
        }

    }
}, null, this);
if (this.character.alive) {
    if (this.cursors.left.isDown) {
        this.character.body.velocity.x = -200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = -1;
    } else if (this.cursors.right.isDown) {
        this.character.body.velocity.x = 200;
        if (standing) this.character.animations.play('run');
        this.character.scale.x = 1;
    } else {
        this.character.body.velocity.x = 0;
        if (standing) this.character.animations.play('stand');
    }
}

 

And finally, we add the ability to revive and send your character to start position by pressing SPACEBAR (set the character coordinates to your starting coordinates, viewed in the Map Editor):

 

if (this.space.isDown && !this.character.alive) {
    this.character.revive();
    this.character.x = 68;
    this.character.y = 452;
}

 

Achieving the Goal

 

One last thing - making the game do something when touching the big chest. This time we won't be using physics but check for overlapping differently (viable for single sprites only, not groups). First, add this checkOverlap function after the update method (don't forget to add a coma after the ending brace of the update method):

 

checkOverlap: function(spriteA, spriteB) {
    var boundsA = spriteA.getBounds();
    var boundsB = spriteB.getBounds();
    return Phaser.Rectangle.intersects(boundsA, boundsB);
}

 

And finally - call this function from within update:

 

if (this.checkOverlap(this.character, this.chest)) {
    this.game.state.start("play");
}

 

In this case, the 'play' state is restarted as soon as you touch the chest.

 

Congratulations!

 

Your game is now be fully playable and the code should closely resemble this:

 

"use strict";
window.SockMan.state.play = {
    create: function() {
        this.bg = mt.create("bg");
        this.character = mt.create("character");
        this.spikes = mt.create("spikes");
        this.chest = mt.create("chest");
        this.objects = mt.create("objects");
        this.coins = mt.create("coins");
        this.gold = mt.create("gold");

        this.cursors = this.game.input.keyboard.createCursorKeys();
        this.space = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

        this.character.animations.add('stand', [0, 1, 2, 3], 10, true);
        this.character.animations.add('run', [6, 7, 8, 9, 10, 11], 10, true);
        this.character.animations.add('jump', [12, 13], 10, false);
        this.character.animations.add('die', [18, 19], 10, false);
        this.character.animations.play('stand');
        this.coins.self.callAll('animations.add', 'animations', 'collect', [7, 8], 10, false);
    },

    update: function() {
        var standing = false;
        this.game.physics.arcade.collide(this.character, this.objects.self, function(character, object) {
            if (object.body.touching.up) {
                standing = true;
            } else standing = false;
            if ((this.space.isDown || this.cursors.up.isDown) && character.alive) {
                if (object.body.touching.up) {
                    this.character.animations.play('jump');
                    this.character.body.velocity.y = -550;
                    standing = false;
                }
            }
        }, null, this);
        if (this.character.alive) {
            if (this.cursors.left.isDown) {
                this.character.body.velocity.x = -200;
                if (standing) this.character.animations.play('run');
                this.character.scale.x = -1;
            } else if (this.cursors.right.isDown) {
                this.character.body.velocity.x = 200;
                if (standing) this.character.animations.play('run');
                this.character.scale.x = 1;
            } else {
                this.character.body.velocity.x = 0;
                if (standing) this.character.animations.play('stand');
            }
        }

        this.game.physics.arcade.overlap(this.character, this.coins.self, function(character, coin) {
            coin.body = null;
            var coinCollect = coin.animations.play('collect');
            coinCollect.killOnComplete = true;
            var newPoints = parseInt(this.gold._text) + 1;
            this.gold.setText(newPoints);
        }, null, this);

        this.game.physics.arcade.collide(this.character, this.spikes.self, function(character, spike) {
            if (character.alive) character.animations.play('die');
            character.body.velocity.x = 0;
            character.body.velocity.y = 0;
            character.alive = false;
        }, null, this);

        if (this.space.isDown && !this.character.alive) {
            this.character.revive();
            this.character.x = 68;
            this.character.y = 452;
        }

        if (this.checkOverlap(this.character, this.chest)) {
            this.game.state.start("play");
        }
    },

    checkOverlap: function(spriteA, spriteB) {
        var boundsA = spriteA.getBounds();
        var boundsB = spriteB.getBounds();
        return Phaser.Rectangle.intersects(boundsA, boundsB);
    }
};

 

Full game project: http://mightyeditor.mightyfingers.com/#pe45-copy

Final game: http://mightyeditor.mightyfingers.com/data/projects/pe45/phaser/index.html

The end result:

 

Click here to open in a new window.

Programming


23. September 2014

 

 

In the previous particle tutorial I used something called a tween followed by the instructions “don’t worry about it, I will cover them later”.  Well, welcome to later!

 

First off, what exactly is a tween?  It’s actually probably exactly what you expect it is, basically it’s “between” turned into a verb.  Tweens are all about transitioning from one state to another, and they are incredibly handy.  Let’s just straight in with an example:

 

/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    sprite: Phaser.Sprite;
    
    constructor() {
        this.game = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
        });
    }
    preload() {
        this.game.load.image("decepticon", "decepticon.png");
        
    }
    render() {
    }
    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to(
            { x: 400 }, 5000, Phaser.Easing.Linear.None, true, 0, Number.MAX_VALUE, true);
    }
}

window.onload = () => {
    var game = new SimpleGame();
};

 

This example shows a to() tween, which is it tweens between the initial value and the value you specify.  When creating a tween, you pass in the option you wish to tween, in this case a Phaser.Sprite.  The first value are the properties we wish to tween, in this cases sprite’s x value.  Next we tell it how long to take ( 5 seconds ), then pass in the easing function we want to use, in this case none ( which by the way, would have been the default value ), next is the delay before beginning ( right away ), how many times to perform ( infinite ) the tween, then finally we pass true to bounce.  Bounce says after you are done the tween, go back to the beginning.

 

And here is the result

 

 

As you can see the image moves across the screen until it’s x value is 400.

 

Now let’s take a look at how the easing function affects the tween.  Instead of no easing function, let’s apply an elastic band type affect.  We use InOut, which means it will ease at the beginning and end of the Tween.

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to({ x: 400 }, 5000,
            Phaser.Easing.Elastic.InOut, true, 0, Number.MAX_VALUE, true);
    }

 

And the result:

 

 

Tweens don't have to be limited to positioning items either, you can tween just about any value. For example, let’s instead tween the alpha value of our sprite:

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite).to({alpha:0 }, 5000,
            Phaser.Easing.Quadratic.In, true, 0, Number.MAX_VALUE, true);
    }

 

And the result

 

 

You can also chain together tweens to perform a series of transitions:

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        this.game.add.tween(this.sprite)
            .to({ x: 400 }, 2000)
            .to({ y: 250 }, 2000)
            .to({ x: 0 }, 2000)
            .to({ y: 0 }, 2000).loop().start();
    }

 

Resulting in:

 

 

Tweens also have event handlers attached. Here for example is a tween that has an onStart and onComplete event handler, that fire before and after the tween completes respectively.

 

    create() {
        this.sprite = this.game.add.sprite(0, 0, "decepticon");
        var tween = this.game.add.tween(this.sprite);
        tween.to({ x: 400 });

        tween.onStart.addOnce(() => {
            this.sprite.scale.setMagnitude(0.5);
        });
        tween.onComplete.addOnce(() => {
            this.game.add.tween(this.sprite).to({ x: 0 }).start();
            },this);
        tween.start();
    }

 

Tweens provide a pretty powerful but simple way of adding actions, either in sequence or parallel, to your game’s contents.

 

Programming


GFS On YouTube

See More Tutorials on DevGa.me!

Month List