diff --git a/README.md b/README.md index 5c2daaefe..fa1cc844e 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,20 @@ -![Phaser Logo](http://www.photonstorm.com/wp-content/uploads/2013/09/phaser_10_release.jpg) +![Phaser 2.0](http://www.phaser.io/images/phaser2-github.png) -Phaser 2.0.0-dev -================ +Phaser 2.0.0 +============ Phaser is a fast, free and fun open source game framework for making desktop and mobile browser HTML5 games. It uses [Pixi.js](https://github.com/GoodBoyDigital/pixi.js/) internally for fast 2D Canvas and WebGL rendering. -Version: 2.0.0 "Aes Sedai" - Released: -in development- +Version: 2.0.0 "Aes Sedai" - Released: March 13th 2014 By Richard Davey, [Photon Storm](http://www.photonstorm.com) * View the [Official Website](http://phaser.io) * Follow on [Twitter](https://twitter.com/photonstorm) * Join the [Forum](http://www.html5gamedevs.com/forum/14-phaser/) -* Try out 220+ [Phaser Examples](http://examples.phaser.io) +* Source code for 250+ [Phaser Examples](https://github.com/photonstorm/phaser-examples) * Read the [documentation online](http://docs.phaser.io) +* Browse the [Examples online](http://examples.phaser.io) * Join our [#phaserio IRC channel](http://www.html5gamedevs.com/topic/4470-official-phaserio-irc-channel-phaserio-on-freenode/) on freenode [Subscribe to our new Phaser Newsletter](https://confirmsubscription.com/h/r/369DE48E3E86AF1E). We'll email you when new versions are released as well as send you our regular Phaser game making magazine. @@ -24,7 +25,17 @@ By Richard Davey, [Photon Storm](http://www.photonstorm.com) Welcome to Phaser ----------------- -Phaser 2.0 "welcome" text to go here. +Exactly 6 months ago we released Phaser 1.0 into the world. Suffice to say that since then we've been overwhelmed at the huge surge of developers taking to it! Our github repository is consistently in the top JavaScript lists, we've over 3200 stars at the time of writing, and a wonderful, vibrant and friendly community. Phaser 2 is a natural evolution of what we started. We've focused specifically on performance and expansion with this release. Lots of developers have already reported to us considerably speed increases just by swapping to Phaser 2 (reports of 200% faster speeds on mobile aren't unheard of!). There's also a full-body physics system available now, in the form of the excellent p2.js. The upgrade to Pixi 1.5 under the hood bought lots of new visual effects in, including blend modes and tints. + +And we're also really pleased to have closed down over 550 issues reported on github. We literally went through every last bug reported to us, and fixed it. All kinds of little things that as a whole make the library that much more solid. With the 2.0 release we're now freezing the API. Before we have to admit that the API changed somewhat on a whim, and we moved things around and changed things without too much consideration for fellow developers. With 2.0 that stops - we've spent long enough on this release that we're now extremely happy with the organisation of classes and methods, and while we may still need to make small tweaks in the future, none of them will be API breaking without prior community approval first. This means if you're using Phaser to teach in classes, or writing a book / tutorials around it, this is the version to base off. + +If you want to port a Phaser 1.x game over to 2 then please see our [Migration Guide]() for help. + +So what's next? We do have a roadmap (which you can find at the bottom of this document), but we're going to sit back and take stock for a while, building up the tutorials and sample games. We will of course jump on bug fixes quickly, and we appreciate that our TypeScript definitions are now slightly out of date again (an eternal quest we appear to be on!), but this is definitely the best release of Phaser ever. The most features, the fastest, the most stable and just generally the most fun to use. + +Happy coding everyone! See you on the forums. + +![boogie](http://www.phaser.io/images/spacedancer.gif) Getting Started Guides @@ -37,61 +48,14 @@ There is a comprehensive [How to Learn Phaser](http://gamedevelopment.tutsplus.c There is also an [un-official Getting Started Guide](http://www.antonoffplus.com/coding-an-html5-game-for-30-minutes-or-an-introduction-to-the-phaser-framework). +![Phaser Logo](http://www.photonstorm.com/wp-content/uploads/2013/09/phaser_10_release.jpg) + Change Log ---------- -Version 2.0.0 - "Aes Sedai" - -in development- - -Significant API changes: - -* Upgraded to Pixi.js 1.5.5 -* Group now extends PIXI.DisplayObjectContainer, rather than owning a _container property, which makes life a whole lot easier re: nesting and child iteration. -* Removed Sprite.group property. You can use Sprite.parent for all similar needs now. -* PIXI.Point is now aliased to Phaser.Point - saves on code duplication and works exactly the same. -* PIXI.Rectangle is now aliased to Phaser.Rectangle - saves on code duplication and works exactly the same. -* PIXI.Circle is now aliased to Phaser.Circle - saves on code duplication and works exactly the same. -* Sprite.deltaX and deltaY swapped to functions: Sprite.deltaX() and Sprite.deltaY() -* Sprite.crop() now takes a Phaser.Rectangle instead of explicit parameters. -* PixiPatch no longer needed, all features that it patched are now native in Pixi :) -* Removed: Sprite.offset, center, topLeft, topRight, bottomRight, bottomLeft and bounds, as no longer needed internally. Use Sprite.getBounds() to derive them. -* Button now extends Phaser.Image not Phaser.Sprite, all the same functionality as before remains, just no animations or physics body. -* Text.content has been replaced with Text.text. The Text class has a lot of new methods, check the docs! -* Loader won't set crossOrigin on Images unless it's set to something. The default is false, it used to be '' and can be any valid string. -* Sprite.input.pixelPerfect has been split into two: Sprite.input.pixelPerfectClick and Sprite.input.pixelPerfectOver (see new features) -* Phaser.Stage now extends PIXI.Stage, rather than containing a _stage object. -* If you set Sprite.exists to false it will also set Sprite.visible to false and remove its body from the physics world (if it has one). -* If you set Sprite.exists to true it will also set Sprite.visible to true and add its body back into the physics world (if it has one). -* Stage.scale has been moved to Game.scale. The same game scaling properties exist as before, but now accessed via Game.scale instead. -* Stage.aspectRatio has been moved to StageScaleMode.sourceAspectRatio (so now game.scale.sourceAspectRatio) -* Stage.scaleMode has been moved to StageScaleMode.scaleMode (so now game.scale.scaleMode) -* Stage.fullScreenScaleMode has been moved to StageScaleMode.fullScreenScaleMode (so now game.scale.fullScreenScaleMode) -* Stage.canvas has been moved to Game.canvas (which used to be a reference to Stage.canvas, but is now the actual object). -* BitmapData.addTo removed and enhanced BitmapData.add so it can accept either a single Sprite/Image or an Array of them. -* BitmapData has had all of the EaselJS functions removed. It was just taking up space and you can do it all via BitmapData.context directly. -* BitmapText has had a bit of an overhaul - the signature for adding a BitmapText has changed to: x, y, font, text, size. See the docs and examples for details. -* World preUpdate, update and postUpdate have all been moved to Stage. So all children are updated regardless where on the display list they live. -* Cache.getImageKeys and similar has been removed, please use Cache.getKeys(Phaser.Cache.IMAGE) instead, this now supports all 10 Cache data types. -* After defining tiles that collide on a Tilemap, you need to call Tilemap.generateCollisionData(layer) to populate the physics world with the data required. -* Phaser.QuadTree has been made more generic and works with any rectangle, not just physics bodies. -* Phaser.Animation.frame now returns the frame of the current animation, rather than the global frame from the sprite sheet / atlas. -* When adding a Group if the parent value is `null` the Group won't be added to the World, so you can add it when ready. If parent is `undefined` it's added by default. -* The Keyboard class has had a complete overhaul. Phaser.Key objects are created automatically, there are fixes against duration and keys reset properly on visibility loss. -* Keyboard.removeKey has been removed. The way the new keyboard manager works means it's no longer required. -* When a game un-pauses (from a visibility loss) it resets all Input components. -* Time.advancedTiming is a new boolean property. If true Time.fps, fpsMin, fpsMax, frames, msMin and msMax will be calculated, otherwise they remain at their defaults. -* Phaser.StageScaleMode has been renamed to ScaleManager and moved from the system folder to the core folder. It's still available under game.scale. -* If your game references the old Phaser.StageScaleMode consts like SHOW_ALL you need to update them to Phaser.ScaleManager, i.e. Phaser.ScaleManager.SHOW_ALL. -* Time.physicsElapsed is no longer bound or clamped, be wary of this if you use the value anywhere in your code. -* In Group.destroy the default for 'destroyChildren' was false. It's now `true` as this is a far more likely requirement when destroying a Group. -* Game no longer pauses if you've forced orientation and change it, also doesn't resize a NO_SCALE game. -* All the Debug methods have had the word 'render' removed from the start. So where you did `debug.renderSpriteInfo` before, it's now just `debug.spriteInfo`. -* Debug methods that rendered geometry (Rectangle, Circle, Line, Point) have been merged into the single method: `Debug.geom`. -* Animation.looped has been renamed to Animation.loop. It's a boolean you can toggle at run-time to turn on/off animation looping. -* Sprite.damage will now kill the Sprite if health is less than or equal to 0 (before it would only kill if less than zero) -* By default Sprites no longer check if they are within the world bounds. It's quite an expensive process (calling getBounds every frame), so you have to enable directly. -* The main Game class has been modified so that the update methods no longer have any if/else checks in them. Now split into coreUpdate, etc. -* RandomDataGenerator is now started on Game creation instead of boot. You can pass a seed array in the game config object (feature request #547) +Version 2.0.0 - "Aes Sedai" - March 13th 2014 +There is an extensive Migration Guide available. In the guide we detail the API breaking changes and approach to our new physics system. The following is a list of all the other new features, updates and bug fixes present in this release. New features: @@ -239,12 +203,6 @@ Bug Fixes: * Cache.destroy fixed to clear up properly (thanks Dumtard, #537) -TO DO: - -* If you change the frame name of a pixel precise input Sprite, it will fail all clicks on it after the frame change. - - - You can view the Change Log for all previous versions at https://github.com/photonstorm/phaser/changelog.md @@ -297,13 +255,19 @@ Games created with Phaser require a modern web browser that supports the canvas For developing with Phaser you can use either a plain-vanilla JavaScript approach or [TypeScript](https://typescript.codeplex.com/) using the provided TypeScript definitions file. We made no assumptions about how you like to code your games, and were careful not to impose any form of class/inheritance/structure upon you. -Phaser is 321 KB minified and 72 KB gzipped. +Phaser is 576 KB minified (including all 3 physics engines, 311KB without) and 128 KB gzipped (67KB without). Learn By Example ---------------- -Phaser comes with an ever growing suite of Examples. Personally I feel that we learn better by looking at small refined code examples, so we created over 200 of them and create new ones to test every new feature added. Inside the `examples` folder you'll find the current set. If you write a particularly good example then please send it to us. +Ever since we started Phaser we've been growing and expanding our extensive set of Examples. Currently over 250 of them! + +They used to be bundled in the main Phaser repo, but because they got so large and in order to help with versioning we've moved them to their own repo. + +Please go and checkout https://github.com/photonstorm/phaser-examples + +Phaser comes with an ever growing suite of Examples. Personally I feel that we learn better by looking at small refined code examples, so we created over 250 of them and create new ones to test every new feature added. Inside the `examples` repo you'll find the current set. If you write a particularly good example then please send it to us. The examples need to be run through a local web server (in order to avoid file access permission errors from your browser). You can use your own web server, or start the included web server using grunt. @@ -315,7 +279,7 @@ Alternatively in order to start the included web server, after you've cloned the There is a new 'Side View' example viewer as well. This loads all the examples into a left-hand frame for faster navigation. -You can also browse all [Phaser Examples](http://gametest.mobi/phaser/) online. +You can also browse all [Phaser Examples](http://examples.phaser.io) online. Features @@ -331,7 +295,7 @@ We've made the loading of assets as simple as one line of code. Images, Sounds, **Physics** -Phaser ships with our Arcade Physics system. A SAT based collision and physics library perfect for low-powered devices and fast collision response. Control velocity, acceleration, bounce, damping and full collision and separation control. As of version 1.1.4 we now support rectangles, circles and polygon collision with full rotation. +Phaser ships with our Arcade Physics system, Ninja Physics and P2.JS - a full body physics system. Arcade Physics is for high-speed AABB collision only. Ninja Physics allows for complex tiles and slopes, perfect for level scenery, and P2.JS is a full-body physics system, with constraints, springs, polygon support and more. **Sprites** @@ -384,7 +348,7 @@ We use Phaser every day on our many client projects. As a result it's constantly **Battle Tested** -Although Phaser 1.0 is a brand new release it is born from years of experience building some of the biggest mobile HTML5 games out there. We're not saying it is 100% bug free, but we use it for our client work every day, so issues get resolved fast and we stay on-top of the changing browser landscape. +Phaser has been used to create hundreds of games, which receive millions of plays per month. We're not saying it is 100% bug free, but we use it for our client work every day, so issues get resolved fast and we stay on-top of the changing browser landscape. ![FruitParty](http://www.photonstorm.com/wp-content/uploads/2013/10/phaser_fruit_particles-640x480.png) diff --git a/examples/_site/css/desert.css b/examples/_site/css/desert.css deleted file mode 100644 index 89bc279b5..000000000 --- a/examples/_site/css/desert.css +++ /dev/null @@ -1,34 +0,0 @@ -/* desert scheme ported from vim to google prettify */ -pre.prettyprint { display: block; background-color: #333 } -pre .nocode { background-color: none; color: #000 } -pre .str { color: #ffa0a0 } /* string - pink */ -pre .kwd { color: #f0e68c; font-weight: bold } -pre .com { color: #87ceeb } /* comment - skyblue */ -pre .typ { color: #98fb98 } /* type - lightgreen */ -pre .lit { color: #cd5c5c } /* literal - darkred */ -pre .pun { color: #fff } /* punctuation */ -pre .pln { color: #fff } /* plaintext */ -pre .tag { color: #f0e68c; font-weight: bold } /* html/xml tag - lightyellow */ -pre .atn { color: #bdb76b; font-weight: bold } /* attribute name - khaki */ -pre .atv { color: #ffa0a0 } /* attribute value - pink */ -pre .dec { color: #98fb98 } /* decimal - lightgreen */ - -/* Specify class=linenums on a pre to get line numbering */ -ol.linenums { margin-top: 0; margin-bottom: 0; color: #AEAEAE } /* IE indents via margin-left */ -li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8 { list-style-type: none } -/* Alternate shading for lines */ -li.L1,li.L3,li.L5,li.L7,li.L9 { } - -@media print { - pre.prettyprint { background-color: none } - pre .str, code .str { color: #060 } - pre .kwd, code .kwd { color: #006; font-weight: bold } - pre .com, code .com { color: #600; font-style: italic } - pre .typ, code .typ { color: #404; font-weight: bold } - pre .lit, code .lit { color: #044 } - pre .pun, code .pun { color: #440 } - pre .pln, code .pln { color: #000 } - pre .tag, code .tag { color: #006; font-weight: bold } - pre .atn, code .atn { color: #404 } - pre .atv, code .atv { color: #060 } -} \ No newline at end of file diff --git a/examples/_site/css/phaser-examples.css b/examples/_site/css/phaser-examples.css deleted file mode 100644 index c3ffec32b..000000000 --- a/examples/_site/css/phaser-examples.css +++ /dev/null @@ -1,196 +0,0 @@ -/* reset css starts */ -html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline;} -/* HTML5 display-role reset for older browsers */ -article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {display: block;} -body {line-height: 1;} -ol, ul {list-style: none;} -blockquote, q {quotes: none;} -blockquote:before, blockquote:after, q:before, q:after {content: ''; content: none;} -table {border-collapse: collapse; border-spacing: 0;} -/* reset css ends */ -@font-face{font-family: 'HelveticaBd'; src: url('../../_site/fonts/HelveticaNeueLTStd-Bd.otf');} - -body { margin:0; padding:0; overflow-x: hidden; font-family: Arial, Tahoma, Verdana !important; background: #e0e4f1;} - -a{color:#fff; text-decoration: none;} -a:hover{text-decoration: underline;} - -.helvetica{font-family: Arial, Tahoma, Verdana !important;} -.header{background: #e0e4f1 url('../../_site/images/header-bg2.jpg') no-repeat; width:100%; margin:0; padding:0; background-size: cover; height: 530px; display: block; clear:both; margin-bottom: -400px} -.main-container{display: block; clear:both; width: 1125px; height: auto; margin:0 auto;} - -ul.nav-links{ margin:0; padding:0; display: inline-block; float: right; list-style-type: none; color: #fff; font-size: 15px; line-height: 2em; margin-top: 50px; min-width: 180px;} -ul.nav-links > li{margin:0; padding:0; list-style-type: none; padding-left: 55px;} -ul.nav-links > li > a{color: #fff; text-decoration: none;} -ul.nav-links > li > a:hover{text-decoration: underline;} -.link-home, .link-latest, .link-forum, .link-docs, .link-twitter{background-image: url('../../_site/images/nav-icons.png'); background-repeat: no-repeat;} - -.main-title{font-family: 'HelveticaBd', Helvetica, Arial;font-size:55px;color:#fff;text-shadow:0 0 15px #b643e6; text-align: center; display: block; margin: 40px auto 0 auto;} -.link-home{background-position: 0 -9px;} -.link-latest{background-position: 0 -37px;} -.link-forum{background-position: 0 -67px;} -.link-docs{background-position: 0 -97px;} -.link-twitter{background-position: 0 -127px;} -.phaser-examples{background: url('../../_site/images/phaser-examples.png') no-repeat; display: block; width: 485px; height: 205px; margin: 20px auto;} -.phaser-version{float: right; background: url('../../_site/images/phaser-version.png') no-repeat; display: block; width: 345px; height: 30px; color: #fff; font-size: 11px; text-shadow: 1px 1px #000; right:0; top:0; } -.phaser-version > span{margin-top: 10px; display: inline-block; margin-left: 60px; margin-right: 25px;} -.phaser-version > a {color: #fff; text-decoration: none; background: url('../../_site/images/version-button.png') no-repeat; background-size: cover; display: inline-block; width: 123px; height: 10px; vertical-align: middle; text-align: center;padding-top:11px; padding-bottom: 11px} -.phaser-version > a:hover{text-decoration: underline;} -.phaser-logo{display: block; float: right; width: 168px;height: 144px; background: url('../../_site/images/phaser-logo.png') no-repeat; margin-top: 40px; margin-right: 40px;} - -#upgrade { - display: none; -} - -#welcome { - position: absolute; - top: 260px; - left: 40%; - width: 200px; - line-height: 28px; -} - -#welcome p { - text-align: center; - text-shadow: 1px 1px 0 #fff; -} - -#welcome a { - color: #7a50c4; -} - -.error { margin-left: 48px; width: 700px; background-color: rgb(150,25,25); color:#fff; text-shadow: 1px 1px 0 #000; line-height: 24px } - -.error p { - padding: 16px 24px; -} - -#title { - text-transform: capitalize; -} - -.line{display:block;clear:both; width:100%; margin:0;padding:0; float:left; background-color: transparent;} -.box5, .box10, .box15 .box20, .box25, .box30, .box35, .box40, .box45, .box50, .box55, .box60, .box65, .box70, .box75, .box80, .box85, .box90, .box95, .box100{position: relative;display: inline-block; box-sizing: border-box; padding: 5px 10px; -moz-box-sizing: border-box; vertical-align: top; margin:0;} -.float-right{float:right !important;} - -.box5{width:4%; min-width: 100px; float:left;} -.box10{width:9%; min-width: 100px; float:left;} -.box15{width:14%; min-width: 150px;float:left;} -.box20{width:19%; min-width: 200px;float:left;} -.box25{width:24%; min-width: 250px;float:left;} -.box30{width:29%; min-width: 300px;float:left;} -.box35{width:34%; min-width: 350px;float:left;} -.box40{width:39%; min-width: 400px;float:left;} -.box45{width:44%; min-width: 450px;float:left;} -.box50{width:49%; min-width: 500px;float:left;} -.box55{width:54%; min-width: 550px;float:left;} -.box60{width:59%; min-width: 600px;float:left;} -.box65{width:64%; min-width: 650px;float:left;} -.box70{width:69%; min-width: 700px;float:left;} -.box75{width:74%; min-width: 750px;float:left;} -.box80{width:79%; min-width: 800px;float:left;} -.box85{width:84%; min-width: 850px;float:left;} -.box90{width:89%; min-width: 900px;float:left;} -.box95{width:94%; min-width: 950px;float:left;} -.box100, .clear, .clear5, .clear10, .clear15, .clear20, .clear25{width:100%; clear: both;} -.clear{display: block;} -.clear5{height: 10px;} -.clear10{height: 20px;} -.clear15{height: 30px;} -.clear20{height: 40px;} -.clear25{height: 50px;} -.strong{text-transform: uppercase !important;} -.no-margin{margin:0 !important;} -.no-padding{padding:0 !important;} -.box-center{float: none !important; margin-left: auto !important; margin-right: auto !important;} -.txt-center{text-align: center !important;} - -p.title{font-family: 'HelveticaBd', Helvetica, Arial; font-size: 30px; color: #fff; text-shadow: 0 1px 3px #9e6ce8; text-align: right;} -p.count-examples{font-size: 12px; color: #676773; text-align: right;} - -ul.group-items{background-image: url('../../_site/images/laser1.png'); background-repeat: no-repeat; background-position: left top 5px; padding-left: 125px; width: 875px !important;} -ul.group-items > li{width: 213px; padding-top: 15px; height: 35px; background: url('../../_site/images/group-item.png') no-repeat; text-align: center; display: inline-block; margin-bottom: 15px} -ul.group-items > li a{display:block; width:100%; height: 100%; padding: 20px 0; margin-top: -20px; color:#333;} -ul.group-items > li a:hover{cursor: pointer; text-decoration: underline;} -ul.group-items > li a span.mark{display:inline-block;width: 1px; height: 25px; vertical-align: middle;} -ul.group-items > li a:visited span.mark{background: url('../../_site/images/group-item-hover.png') no-repeat; background-position: center center;width:25px; padding-left:4px;} - -.laser2{background-image: url('../../_site/images/laser2.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser3{background-image: url('../../_site/images/laser3.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser4{background-image: url('../../_site/images/laser4.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser5{background-image: url('../../_site/images/laser5.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser6{background-image: url('../../_site/images/laser6.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser7{background-image: url('../../_site/images/laser7.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser8{background-image: url('../../_site/images/laser8.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser9{background-image: url('../../_site/images/laser9.png') !important; background-repeat: no-repeat; background-position: center 20px;} -.laser10{background-image: url('../../_site/images/laser10.png') !important; background-repeat: no-repeat; background-position: center 20px;} - -.bright-bg, .dark-bg{border-bottom: 1px solid #d1d1d1; padding:25px 0;} - -.border-bottom{border-bottom: 1px solid #d1d1d1;} - -.prize-bg{background: url('../../_site/images/prize-bg.png') no-repeat; background-size: cover; background-position: center center; height: 326px; width: 100%;} -.prize-button{text-transform: uppercase; color: #000; text-shadow: 1px 0 #fff; float:right; background: url('../../_site/images/prize-button.png') no-repeat; width: 300px; height: 70px; padding-top:135px; font-size: 16px; padding-left: 75px; margin-top: 25px; margin-right: 145px;} - -.footer{ background: #e0e4f1 url('../../_site/images/footer-bg2.jpg') no-repeat; background-size: cover; width:100%; height: 592px; bottom:0; } -.photonstorm-logo{background: url('../../_site/images/photonstorm-logo.png') no-repeat; background-size: cover; display: block;clear:both; width:113px;height:15px; margin-bottom: 6px;} -.flixel-logo{display:block; clear:both; width:26px; height:50px; background: url('../../_site/images/flixel-logo.png') no-repeat;} -.forums-icon, .twitter-icon, .github-icon{background: url('../../_site/images/forums-icon.png') no-repeat; vertical-align: middle; padding-left: 68px; height: 35px; display: inline-block; padding-top: 25px;} -.twitter-icon{background: url('../../_site/images/twitter-icon.png') no-repeat;} -.github-icon{background: url('../../_site/images/github-icon.png') no-repeat;} - -#footer .main-container .line { - margin-top: 130px; - color:#fff; text-shadow: 1px 1px 0 #000; line-height: 1.25em; font-size: 15px; -} - -ul.footer-links{list-style-type: none; width:100%; clear:both; padding:0; margin:0; float:right; margin-top: -20px;} -ul.footer-links > li{display: inline-block; padding:0; margin:0; float:right;} - -.game-panel{width:800px; height: 680px; overflow: hidden; display:block; clear:both;box-shadow: 0 0 15px #6ac8f8; margin:-150px auto 0 auto; border-radius: 10px; position: relative; z-index: 10;} -.game-screen{display:block; clear:both; width:800px;height:600px;margin:0;} -.game-controls{display:block; width:100%; height:80px; margin:0; padding:0;background: url('../../_site/images/game-controls-bg.jpg') repeat-x;} -ul.left-controls{float:left; list-style-type: none; margin:30px 0 0 25px;padding:0; display: inline-block;} -ul.left-controls > li{margin:0;padding:0; display: inline-block; vertical-align: middle;} -.controls-label{display:inline-block; width:80px; height:9px; background: url('../../_site/images/controls-label.png') no-repeat;} -.up-label{display: inline-block; width:11px; height: 11px; background: url('../../_site/images/up-label.png') no-repeat;} -.down-label{display: inline-block; width:11px; height: 11px; background: url('../../_site/images/down-label.png') no-repeat;} -.left-label{display: inline-block; width:13px; height: 11px; background: url('../../_site/images/left-label.png') no-repeat;} -.right-label{display: inline-block; width:12px; height: 11px; background: url('../../_site/images/right-label.png') no-repeat;} -.space-label{display: inline-block; width:64px; height: 18px; background: url('../../_site/images/space-label.png') no-repeat;} - -ul.right-controls{float:right;list-style-type: none; padding:0; display: inline-block; margin: 15px 25px 0 0;} -ul.right-controls > li{margin:0;padding:0; display: inline-block; vertical-align: middle;} -.pause-button{width: 121px; height:52px; display:inline-block; background: url('../../_site/images/pause-button.png') no-repeat;} -.mute-button{width: 121px; height:52px; display:inline-block; background: url('../../_site/images/mute-button.png') no-repeat;} -.reset-button{width: 121px; height:52px; display:inline-block; background: url('../../_site/images/reset-button.png') no-repeat;} -.pause-button:hover, .mute-button:hover, .reset-button:hover{cursor: pointer;} -.filler{height: 720px;} -.code-block{font-family: Courier; font-size: 12px; color: #fff; width:750px; height:auto; overflow: scroll; margin:0 auto; border-radius: 10px; background:#fdfdfd; border:0 !important; box-shadow: inset 0 5px 15px rgba(0,0,0,0.15), 0 0 10px rgba(106,200,248,0.5); padding: 25px !important;display: block; margin-bottom: 20px; margin-top: 30px;} -.px800{width:800px; clear:both; display: block; margin:0 auto; line-height: 1.5em;} -.gradient p{color:#333;} - -@media only screen and (max-width: 1235px), only screen and (max-device-width: 1235px){ - ul.nav-links{min-width:100% !important;} - ul.nav-links > li{display: inline-block;} -} -@media only screen and (max-width: 1120px), only screen and (max-device-width: 1120px){ - .footer .box20, .footer .box55, .footer .box15{display: block; clear:both; margin:10px auto; text-align: center; float:none;} - .footer .box5{display:none;} - .photonstorm-logo{margin:10px auto;} - .footer .box55{width:100%; float:none; margin:10px auto;} - .footer ul.footer-links{width:100%;} - .footer ul.footer-links > li{float:none;} - .footer > .main-container > .line{margin-top: 125px;} -} -@media only screen and (max-width: 1020px), only screen and (max-device-width: 1020px){ - .phaser-logo{display:none;} - .header{margin-bottom: -350px;} - p.title, p.count-examples{text-align: center;} - .box20, .box60{min-width:100% !important; clear:both; width: 100% !important; max-width: 100% !important; text-align: center;} - a.prize-button{margin:0 auto; float:none;display:block;} - .prize-bg{background: transparent;} -} -@media only screen and (max-width: 810px), only screen and (max-device-width: 810px){ - .main-container{width:100%;} -} \ No newline at end of file diff --git a/examples/_site/css/phaser-lite.css b/examples/_site/css/phaser-lite.css deleted file mode 100644 index ce1d4bdf6..000000000 --- a/examples/_site/css/phaser-lite.css +++ /dev/null @@ -1,84 +0,0 @@ -@font-face { - - font-family: 'inconsolata'; - src: url('../../_site/fonts/inconsolata.woff') format('woff'); - font-weight: normal; - font-style: normal; - -} - -body { - - background: #e0e4f1; - margin: 0px; - font-family: 'inconsolata'; - font-size: 15px; - overflow: hidden; - -} - -a { - text-decoration: none; - color: #1c99bb; -} - -a:hover { - background-color: #e69b0b; - color: #fff; -} - -h1 { - - font-size: 25px; - font-weight: normal; - -} - -h2 { - - font-size: 20px; - font-weight: normal; - -} - -#header { - background: url(../../_site/images/lite_header.jpg) no-repeat left top; - width: 300px; - height: 100px; -} - -#panel { - - background: url(../../_site/images/lite_header_2.jpg) no-repeat left top; - width: 300px; - overflow-x: hidden; - overflow-y: scroll; - -} - - #panel #examples-list { - - padding: 10px 20px; - line-height: 18px; - - } - -#footer { - background: url(../../_site/images/lite_footer.jpg) no-repeat left top; - width: 300px; - height: 170px; - color: #000; - text-align: center; -} - -#viewer { - - position: absolute; - top: 0px; - left: 300px; - width: -webkit-calc(100% - 300px); /* Safari */ - width: calc(100% - 300px); - height: 100%; - border: 0px; - -} diff --git a/examples/_site/examples.json b/examples/_site/examples.json deleted file mode 100644 index 107a8f32a..000000000 --- a/examples/_site/examples.json +++ /dev/null @@ -1,1068 +0,0 @@ -{ - "animation": [ - { - "file": "animation+events.js", - "title": "animation events" - }, - { - "file": "change+texture+on+click.js", - "title": "change texture on click" - }, - { - "file": "group+creation.js", - "title": "group creation" - }, - { - "file": "local+json+object.js", - "title": "local json object" - }, - { - "file": "looped+animation.js", - "title": "looped animation" - }, - { - "file": "multiple+anims.js", - "title": "multiple anims" - }, - { - "file": "sprite+sheet.js", - "title": "sprite sheet" - }, - { - "file": "starling+atlas.js", - "title": "starling atlas" - } - ], - "arcade physics": [ - { - "file": "accelerate+to+pointer.js", - "title": "accelerate to pointer" - }, - { - "file": "angle+between.js", - "title": "angle between" - }, - { - "file": "angle+to+pointer.js", - "title": "angle to pointer" - }, - { - "file": "angular+acceleration.js", - "title": "angular acceleration" - }, - { - "file": "angular+velocity.js", - "title": "angular velocity" - }, - { - "file": "body+scale.js", - "title": "body scale" - }, - { - "file": "bounce+accelerator.js", - "title": "bounce accelerator" - }, - { - "file": "bounce+knock.js", - "title": "bounce knock" - }, - { - "file": "bounce+with+gravity.js", - "title": "bounce with gravity" - }, - { - "file": "bounce.js", - "title": "bounce" - }, - { - "file": "bounding+box.js", - "title": "bounding box" - }, - { - "file": "gravity.js", - "title": "gravity" - }, - { - "file": "group+vs+group.js", - "title": "group vs group" - }, - { - "file": "group+vs+self.js", - "title": "group vs self" - }, - { - "file": "larger+bounding+box.js", - "title": "larger bounding box" - }, - { - "file": "launcher+follow+world.js", - "title": "launcher follow world" - }, - { - "file": "launcher+follow.js", - "title": "launcher follow" - }, - { - "file": "launcher.js", - "title": "launcher" - }, - { - "file": "mass+velocity+test.js", - "title": "mass velocity test" - }, - { - "file": "move+towards+object.js", - "title": "move towards object" - }, - { - "file": "multi+angle+to+pointer.js", - "title": "multi angle to pointer" - }, - { - "file": "offset+bounding+box.js", - "title": "offset bounding box" - }, - { - "file": "one+way+collision.js", - "title": "one way collision" - }, - { - "file": "process+callback.js", - "title": "process callback" - }, - { - "file": "quadtree+-+collision+infos.js", - "title": "quadtree - collision infos" - }, - { - "file": "ship+trail.js", - "title": "ship trail" - }, - { - "file": "shoot+the+pointer.js", - "title": "shoot the pointer" - }, - { - "file": "snake.js", - "title": "snake" - }, - { - "file": "sprite+vs+group.js", - "title": "sprite vs group" - }, - { - "file": "sprite+vs+sprite.js", - "title": "sprite vs sprite" - }, - { - "file": "vertical+collision.js", - "title": "vertical collision" - } - ], - "audio": [ - { - "file": "loop.js", - "title": "loop" - }, - { - "file": "pause+and+resume.js", - "title": "pause and resume" - }, - { - "file": "play+music.js", - "title": "play music" - }, - { - "file": "protracker.js", - "title": "protracker" - } - ], - "basics": [ - { - "file": "01+-+load+an+image.js", - "title": "01 - load an image" - }, - { - "file": "02+-+click+on+an+image.js", - "title": "02 - click on an image" - }, - { - "file": "03+-+move+an+image.js", - "title": "03 - move an image" - }, - { - "file": "04+-+image+follow+input.js", - "title": "04 - image follow input" - }, - { - "file": "05+-+load+an+animation.js", - "title": "05 - load an animation" - }, - { - "file": "06+-+render+text.js", - "title": "06 - render text" - } - ], - "buttons": [ - { - "file": "action+on+click.js", - "title": "action on click" - }, - { - "file": "button+scale.js", - "title": "button scale" - }, - { - "file": "changing+the+frames.js", - "title": "changing the frames" - }, - { - "file": "rotated+buttons.js", - "title": "rotated buttons" - } - ], - "camera": [ - { - "file": "basic+follow.js", - "title": "basic follow" - }, - { - "file": "camera+cull.js", - "title": "camera cull" - }, - { - "file": "follow+styles.js", - "title": "follow styles" - }, - { - "file": "moving+the+camera.js", - "title": "moving the camera" - }, - { - "file": "world+sprite.js", - "title": "world sprite" - } - ], - "debug": [ - { - "file": "debug+camera.js", - "title": "debug camera" - }, - { - "file": "debug+display.js", - "title": "debug display" - }, - { - "file": "debug+draw.js", - "title": "debug draw" - }, - { - "file": "debug+input.js", - "title": "debug input" - }, - { - "file": "debug+physics.js", - "title": "debug physics" - }, - { - "file": "debug+sprite.js", - "title": "debug sprite" - } - ], - "display": [ - { - "file": "bitmapdata+wobble.js", - "title": "bitmapdata wobble" - }, - { - "file": "fullscreen+buttons.js", - "title": "fullscreen buttons" - }, - { - "file": "fullscreen.js", - "title": "fullscreen" - }, - { - "file": "graphics.js", - "title": "graphics" - }, - { - "file": "pixi+render+texture.js", - "title": "pixi render texture" - }, - { - "file": "render+crisp.js", - "title": "render crisp" - }, - { - "file": "render+texture+mirror.js", - "title": "render texture mirror" - }, - { - "file": "render+texture+starfield.js", - "title": "render texture starfield" - }, - { - "file": "render+texture+trail.js", - "title": "render texture trail" - } - ], - "filters": [ - { - "file": "blur.js", - "title": "blur" - }, - { - "file": "checker+wave.js", - "title": "checker wave" - }, - { - "file": "fire.js", - "title": "fire" - }, - { - "file": "gray.js", - "title": "gray" - }, - { - "file": "lightbeams.js", - "title": "lightbeams" - }, - { - "file": "marble.js", - "title": "marble" - }, - { - "file": "plasma.js", - "title": "plasma" - }, - { - "file": "tunnel.js", - "title": "tunnel" - } - ], - "games": [ - { - "file": "breakout.js", - "title": "breakout" - }, - { - "file": "invaders.js", - "title": "invaders" - }, - { - "file": "matching+pairs.js", - "title": "matching pairs" - }, - { - "file": "simon.js", - "title": "simon" - }, - { - "file": "starstruck.js", - "title": "starstruck" - }, - { - "file": "tanks.js", - "title": "tanks" - } - ], - "geometry": [ - { - "file": "circle.js", - "title": "circle" - }, - { - "file": "line+bounds.js", - "title": "line bounds" - }, - { - "file": "line+intersection.js", - "title": "line intersection" - }, - { - "file": "line.js", - "title": "line" - }, - { - "file": "playing+with+points.js", - "title": "playing with points" - }, - { - "file": "rectangle.js", - "title": "rectangle" - }, - { - "file": "rotate+point.js", - "title": "rotate point" - } - ], - "groups": [ - { - "file": "add+a+sprite+to+group.js", - "title": "add a sprite to group" - }, - { - "file": "bring+a+group+to+top.js", - "title": "bring a group to top" - }, - { - "file": "call+all+animations.js", - "title": "call all animations" - }, - { - "file": "call+all.js", - "title": "call all" - }, - { - "file": "create+group.js", - "title": "create group" - }, - { - "file": "create+sprite+in+a+group.js", - "title": "create sprite in a group" - }, - { - "file": "depth+sort.js", - "title": "depth sort" - }, - { - "file": "display+order.js", - "title": "display order" - }, - { - "file": "extending+a+group.js", - "title": "extending a group" - }, - { - "file": "for+each.js", - "title": "for each" - }, - { - "file": "get+first+dead.js", - "title": "get first dead" - }, - { - "file": "get+first.js", - "title": "get first" - }, - { - "file": "group+as+layer.js", - "title": "group as layer" - }, - { - "file": "group+transform+-+rotate.js", - "title": "group transform - rotate" - }, - { - "file": "group+transform+-+tween.js", - "title": "group transform - tween" - }, - { - "file": "group+transform.js", - "title": "group transform" - }, - { - "file": "nested+groups.js", - "title": "nested groups" - }, - { - "file": "recyling.js", - "title": "recyling" - }, - { - "file": "remove.js", - "title": "remove" - }, - { - "file": "replace.js", - "title": "replace" - }, - { - "file": "set+All.js", - "title": "set All" - }, - { - "file": "sub+groups+-+group+length.js", - "title": "sub groups - group length" - }, - { - "file": "swap+children+in+a+group.js", - "title": "swap children in a group" - } - ], - "input": [ - { - "file": "bring+a+child+to+top.js", - "title": "bring a child to top" - }, - { - "file": "cursor+key+movement.js", - "title": "cursor key movement" - }, - { - "file": "drag+several+sprites.js", - "title": "drag several sprites" - }, - { - "file": "drag.js", - "title": "drag" - }, - { - "file": "drop+limitation.js", - "title": "drop limitation" - }, - { - "file": "follow+mouse.js", - "title": "follow mouse" - }, - { - "file": "game+scale.js", - "title": "game scale" - }, - { - "file": "gamepad+analog+button.js", - "title": "gamepad analog button" - }, - { - "file": "gamepad+debug.js", - "title": "gamepad debug" - }, - { - "file": "gamepad+hotkeys.js", - "title": "gamepad hotkeys" - }, - { - "file": "gamepad+multiple+pads.js", - "title": "gamepad multiple pads" - }, - { - "file": "gamepad+tanks.js", - "title": "gamepad tanks" - }, - { - "file": "gamepad.js", - "title": "gamepad" - }, - { - "file": "key.js", - "title": "key" - }, - { - "file": "keyboard+hotkeys.js", - "title": "keyboard hotkeys" - }, - { - "file": "keyboard+justpressed.js", - "title": "keyboard justpressed" - }, - { - "file": "keyboard.js", - "title": "keyboard" - }, - { - "file": "motion+lock+-+horizontal.js", - "title": "motion lock - horizontal" - }, - { - "file": "motion+lock+-+vertical.js", - "title": "motion lock - vertical" - }, - { - "file": "multi+touch.js", - "title": "multi touch" - }, - { - "file": "override+default+controls.js", - "title": "override default controls" - }, - { - "file": "pixel+perfect+click+detection.js", - "title": "pixel perfect click detection" - }, - { - "file": "pixelpick+-+atlas.js", - "title": "pixelpick - atlas" - }, - { - "file": "pixelpick+-+scrolling+effect.js", - "title": "pixelpick - scrolling effect" - }, - { - "file": "pixelpick+-+spritesheet.js", - "title": "pixelpick - spritesheet" - }, - { - "file": "snap+on+drag.js", - "title": "snap on drag" - }, - { - "file": "touch+joystick.js", - "title": "touch joystick" - } - ], - "loader": [ - { - "file": "load+audio.js", - "title": "load audio" - }, - { - "file": "load+bitmap+font.js", - "title": "load bitmap font" - }, - { - "file": "load+image.js", - "title": "load image" - }, - { - "file": "load+spritesheet.js", - "title": "load spritesheet" - }, - { - "file": "load+starling+atlas.js", - "title": "load starling atlas" - }, - { - "file": "load+text+file.js", - "title": "load text file" - }, - { - "file": "load+texture+atlas.js", - "title": "load texture atlas" - }, - { - "file": "load+tilemap+json.js", - "title": "load tilemap json" - }, - { - "file": "pick+images+from+cache.js", - "title": "pick images from cache" - } - ], - "misc": [ - { - "file": "net.js", - "title": "net" - }, - { - "file": "random+generators.js", - "title": "random generators" - }, - { - "file": "repeatable+random+numbers.js", - "title": "repeatable random numbers" - } - ], - "ninja physics": [ - { - "file": "ninja+aabb+vs+aabb.js", - "title": "ninja aabb vs aabb" - }, - { - "file": "ninja+aabb+vs+tile.js", - "title": "ninja aabb vs tile" - }, - { - "file": "ninja+impact.js", - "title": "ninja impact" - }, - { - "file": "ninja+tilemap.js", - "title": "ninja tilemap" - } - ], - "p2 physics": [ - { - "file": "basic+movement.js", - "title": "basic movement" - }, - { - "file": "body+click.js", - "title": "body click" - }, - { - "file": "collision+groups.js", - "title": "collision groups" - }, - { - "file": "contact+events.js", - "title": "contact events" - }, - { - "file": "distance+constraint.js", - "title": "distance constraint" - }, - { - "file": "gear+constraint.js", - "title": "gear constraint" - }, - { - "file": "gravity.js", - "title": "gravity" - }, - { - "file": "impact+events.js", - "title": "impact events" - }, - { - "file": "kill+and+revive.js", - "title": "kill and revive" - }, - { - "file": "load+polygon+1.js", - "title": "load polygon 1" - }, - { - "file": "load+polygon+2.js", - "title": "load polygon 2" - }, - { - "file": "lock+constraint.js", - "title": "lock constraint" - }, - { - "file": "postbroadphase+callback.js", - "title": "postbroadphase callback" - }, - { - "file": "prismatic+constraint.js", - "title": "prismatic constraint" - }, - { - "file": "revolute+constraint.js", - "title": "revolute constraint" - }, - { - "file": "springs.js", - "title": "springs" - }, - { - "file": "thrust.js", - "title": "thrust" - }, - { - "file": "world+move.js", - "title": "world move" - } - ], - "particles": [ - { - "file": "click+burst.js", - "title": "click burst" - }, - { - "file": "collision.js", - "title": "collision" - }, - { - "file": "diamond+burst.js", - "title": "diamond burst" - }, - { - "file": "no+rotation.js", - "title": "no rotation" - }, - { - "file": "rain.js", - "title": "rain" - }, - { - "file": "random+sprite.js", - "title": "random sprite" - }, - { - "file": "snow.js", - "title": "snow" - }, - { - "file": "when+particles+collide.js", - "title": "when particles collide" - }, - { - "file": "zero+gravity.js", - "title": "zero gravity" - } - ], - "sprites": [ - { - "file": "add+a+sprite.js", - "title": "add a sprite" - }, - { - "file": "add+several+sprites.js", - "title": "add several sprites" - }, - { - "file": "collide+world+bounds.js", - "title": "collide world bounds" - }, - { - "file": "destroy.js", - "title": "destroy" - }, - { - "file": "dynamic+crop.js", - "title": "dynamic crop" - }, - { - "file": "extending+sprite+demo+1.js", - "title": "extending sprite demo 1" - }, - { - "file": "extending+sprite+demo+2.js", - "title": "extending sprite demo 2" - }, - { - "file": "horizontal+crop.js", - "title": "horizontal crop" - }, - { - "file": "move+a+sprite.js", - "title": "move a sprite" - }, - { - "file": "out+of+bounds.js", - "title": "out of bounds" - }, - { - "file": "scale+a+sprite.js", - "title": "scale a sprite" - }, - { - "file": "shared+sprite+textures.js", - "title": "shared sprite textures" - }, - { - "file": "sprite+rotation.js", - "title": "sprite rotation" - }, - { - "file": "spritesheet.js", - "title": "spritesheet" - }, - { - "file": "vertical+crop.js", - "title": "vertical crop" - } - ], - "text": [ - { - "file": "bitmap+fonts.js", - "title": "bitmap fonts" - }, - { - "file": "bitmapfont+drag.js", - "title": "bitmapfont drag" - }, - { - "file": "dynamic+text+shadow.js", - "title": "dynamic text shadow" - }, - { - "file": "google+webfonts.js", - "title": "google webfonts" - }, - { - "file": "hello+arial.js", - "title": "hello arial" - }, - { - "file": "kern+of+duty.js", - "title": "kern of duty" - }, - { - "file": "littera.js", - "title": "littera" - }, - { - "file": "remove+text.js", - "title": "remove text" - }, - { - "file": "retro+font+1.js", - "title": "retro font 1" - }, - { - "file": "retro+font+2.js", - "title": "retro font 2" - }, - { - "file": "set+properties+after+creation.js", - "title": "set properties after creation" - }, - { - "file": "text+gradient.js", - "title": "text gradient" - }, - { - "file": "text+reflect.js", - "title": "text reflect" - }, - { - "file": "text+shadow.js", - "title": "text shadow" - }, - { - "file": "text+stroke.js", - "title": "text stroke" - }, - { - "file": "update+text.js", - "title": "update text" - } - ], - "tile sprites": [ - { - "file": "animated+tiling+sprite.js", - "title": "animated tiling sprite" - }, - { - "file": "colliding+with+tiling+sprite.js", - "title": "colliding with tiling sprite" - }, - { - "file": "tiling+sprite.js", - "title": "tiling sprite" - } - ], - "tilemaps": [ - { - "file": "blank+tilemap.js", - "title": "blank tilemap" - }, - { - "file": "create+from+objects.js", - "title": "create from objects" - }, - { - "file": "csv+map.js", - "title": "csv map" - }, - { - "file": "fill+tiles.js", - "title": "fill tiles" - }, - { - "file": "map+bounce.js", - "title": "map bounce" - }, - { - "file": "map+collide.js", - "title": "map collide" - }, - { - "file": "paint+tiles.js", - "title": "paint tiles" - }, - { - "file": "randomise+tiles.js", - "title": "randomise tiles" - }, - { - "file": "replace+tiles.js", - "title": "replace tiles" - }, - { - "file": "sci+fly.js", - "title": "sci fly" - }, - { - "file": "shuffle+tiles.js", - "title": "shuffle tiles" - }, - { - "file": "swap+tiles.js", - "title": "swap tiles" - }, - { - "file": "tile+callbacks.js", - "title": "tile callbacks" - }, - { - "file": "tilemap+ray+cast.js", - "title": "tilemap ray cast" - } - ], - "time": [ - { - "file": "basic+looped+event.js", - "title": "basic looped event" - }, - { - "file": "basic+repeat+event.js", - "title": "basic repeat event" - }, - { - "file": "basic+timed+event.js", - "title": "basic timed event" - }, - { - "file": "remove+event.js", - "title": "remove event" - }, - { - "file": "timed+slideshow.js", - "title": "timed slideshow" - } - ], - "tweens": [ - { - "file": "bounce.js", - "title": "bounce" - }, - { - "file": "bubbles.js", - "title": "bubbles" - }, - { - "file": "chained+tweens.js", - "title": "chained tweens" - }, - { - "file": "combined+tweens.js", - "title": "combined tweens" - }, - { - "file": "easing+spritesheets.js", - "title": "easing spritesheets" - }, - { - "file": "easing.js", - "title": "easing" - }, - { - "file": "fading+in+a+sprite.js", - "title": "fading in a sprite" - }, - { - "file": "generate+data.js", - "title": "generate data" - }, - { - "file": "pause+tween.js", - "title": "pause tween" - }, - { - "file": "tween+loop+event.js", - "title": "tween loop event" - }, - { - "file": "tween+relative.js", - "title": "tween relative" - }, - { - "file": "tween+several+properties.js", - "title": "tween several properties" - } - ], - "world": [ - { - "file": "fixed+to+camera.js", - "title": "fixed to camera" - }, - { - "file": "move+around+world.js", - "title": "move around world" - } - ] -} \ No newline at end of file diff --git a/examples/_site/fonts/HelveticaNeueLTStd-Bd.otf b/examples/_site/fonts/HelveticaNeueLTStd-Bd.otf deleted file mode 100644 index d4ac7c110..000000000 Binary files a/examples/_site/fonts/HelveticaNeueLTStd-Bd.otf and /dev/null differ diff --git a/examples/_site/fonts/inconsolata.woff b/examples/_site/fonts/inconsolata.woff deleted file mode 100644 index 6170a0bfc..000000000 Binary files a/examples/_site/fonts/inconsolata.woff and /dev/null differ diff --git a/examples/_site/images/bg-footer.jpg b/examples/_site/images/bg-footer.jpg deleted file mode 100644 index 5189cb55d..000000000 Binary files a/examples/_site/images/bg-footer.jpg and /dev/null differ diff --git a/examples/_site/images/controls-label.png b/examples/_site/images/controls-label.png deleted file mode 100644 index 384c986cc..000000000 Binary files a/examples/_site/images/controls-label.png and /dev/null differ diff --git a/examples/_site/images/down-label.png b/examples/_site/images/down-label.png deleted file mode 100644 index 0039d57b4..000000000 Binary files a/examples/_site/images/down-label.png and /dev/null differ diff --git a/examples/_site/images/flixel-logo.png b/examples/_site/images/flixel-logo.png deleted file mode 100644 index cb50f865f..000000000 Binary files a/examples/_site/images/flixel-logo.png and /dev/null differ diff --git a/examples/_site/images/footer-bg.jpg b/examples/_site/images/footer-bg.jpg deleted file mode 100644 index ba8c17ae2..000000000 Binary files a/examples/_site/images/footer-bg.jpg and /dev/null differ diff --git a/examples/_site/images/footer-bg2.jpg b/examples/_site/images/footer-bg2.jpg deleted file mode 100644 index 4811c4508..000000000 Binary files a/examples/_site/images/footer-bg2.jpg and /dev/null differ diff --git a/examples/_site/images/forums-icon.png b/examples/_site/images/forums-icon.png deleted file mode 100644 index 79c1c8b1a..000000000 Binary files a/examples/_site/images/forums-icon.png and /dev/null differ diff --git a/examples/_site/images/game-controls-bg.jpg b/examples/_site/images/game-controls-bg.jpg deleted file mode 100644 index 82e40bf83..000000000 Binary files a/examples/_site/images/game-controls-bg.jpg and /dev/null differ diff --git a/examples/_site/images/github-icon.png b/examples/_site/images/github-icon.png deleted file mode 100644 index e04eb798e..000000000 Binary files a/examples/_site/images/github-icon.png and /dev/null differ diff --git a/examples/_site/images/gradient-bg.jpg b/examples/_site/images/gradient-bg.jpg deleted file mode 100644 index 0669f1040..000000000 Binary files a/examples/_site/images/gradient-bg.jpg and /dev/null differ diff --git a/examples/_site/images/group-item-hover.png b/examples/_site/images/group-item-hover.png deleted file mode 100644 index bf0fc009d..000000000 Binary files a/examples/_site/images/group-item-hover.png and /dev/null differ diff --git a/examples/_site/images/group-item.png b/examples/_site/images/group-item.png deleted file mode 100644 index 9638cad4b..000000000 Binary files a/examples/_site/images/group-item.png and /dev/null differ diff --git a/examples/_site/images/header-bg.jpg b/examples/_site/images/header-bg.jpg deleted file mode 100644 index b5cafc40a..000000000 Binary files a/examples/_site/images/header-bg.jpg and /dev/null differ diff --git a/examples/_site/images/header-bg2.jpg b/examples/_site/images/header-bg2.jpg deleted file mode 100644 index 5dcabec26..000000000 Binary files a/examples/_site/images/header-bg2.jpg and /dev/null differ diff --git a/examples/_site/images/laser1.png b/examples/_site/images/laser1.png deleted file mode 100644 index 4c23aa167..000000000 Binary files a/examples/_site/images/laser1.png and /dev/null differ diff --git a/examples/_site/images/laser10.png b/examples/_site/images/laser10.png deleted file mode 100644 index bf1cc4404..000000000 Binary files a/examples/_site/images/laser10.png and /dev/null differ diff --git a/examples/_site/images/laser2.png b/examples/_site/images/laser2.png deleted file mode 100644 index 61d630837..000000000 Binary files a/examples/_site/images/laser2.png and /dev/null differ diff --git a/examples/_site/images/laser3.png b/examples/_site/images/laser3.png deleted file mode 100644 index 90a74a011..000000000 Binary files a/examples/_site/images/laser3.png and /dev/null differ diff --git a/examples/_site/images/laser4.png b/examples/_site/images/laser4.png deleted file mode 100644 index 2e99d190f..000000000 Binary files a/examples/_site/images/laser4.png and /dev/null differ diff --git a/examples/_site/images/laser5.png b/examples/_site/images/laser5.png deleted file mode 100644 index ee8c3b7e6..000000000 Binary files a/examples/_site/images/laser5.png and /dev/null differ diff --git a/examples/_site/images/laser6.png b/examples/_site/images/laser6.png deleted file mode 100644 index 5bb2d5d58..000000000 Binary files a/examples/_site/images/laser6.png and /dev/null differ diff --git a/examples/_site/images/laser7.png b/examples/_site/images/laser7.png deleted file mode 100644 index d96a5ad90..000000000 Binary files a/examples/_site/images/laser7.png and /dev/null differ diff --git a/examples/_site/images/laser8.png b/examples/_site/images/laser8.png deleted file mode 100644 index 5d086fa1e..000000000 Binary files a/examples/_site/images/laser8.png and /dev/null differ diff --git a/examples/_site/images/laser9.png b/examples/_site/images/laser9.png deleted file mode 100644 index d735325a6..000000000 Binary files a/examples/_site/images/laser9.png and /dev/null differ diff --git a/examples/_site/images/left-label.png b/examples/_site/images/left-label.png deleted file mode 100644 index 8f796dda4..000000000 Binary files a/examples/_site/images/left-label.png and /dev/null differ diff --git a/examples/_site/images/lite_footer.jpg b/examples/_site/images/lite_footer.jpg deleted file mode 100644 index 51549193a..000000000 Binary files a/examples/_site/images/lite_footer.jpg and /dev/null differ diff --git a/examples/_site/images/lite_header.jpg b/examples/_site/images/lite_header.jpg deleted file mode 100644 index 0aa2e2fc3..000000000 Binary files a/examples/_site/images/lite_header.jpg and /dev/null differ diff --git a/examples/_site/images/lite_header_2.jpg b/examples/_site/images/lite_header_2.jpg deleted file mode 100644 index fa1eb718a..000000000 Binary files a/examples/_site/images/lite_header_2.jpg and /dev/null differ diff --git a/examples/_site/images/mute-button.png b/examples/_site/images/mute-button.png deleted file mode 100644 index dccd26af6..000000000 Binary files a/examples/_site/images/mute-button.png and /dev/null differ diff --git a/examples/_site/images/nav-icons.png b/examples/_site/images/nav-icons.png deleted file mode 100644 index faf9201e0..000000000 Binary files a/examples/_site/images/nav-icons.png and /dev/null differ diff --git a/examples/_site/images/pause-button.png b/examples/_site/images/pause-button.png deleted file mode 100644 index c5bcfd387..000000000 Binary files a/examples/_site/images/pause-button.png and /dev/null differ diff --git a/examples/_site/images/phaser-examples.png b/examples/_site/images/phaser-examples.png deleted file mode 100644 index 8900dba6d..000000000 Binary files a/examples/_site/images/phaser-examples.png and /dev/null differ diff --git a/examples/_site/images/phaser-logo.png b/examples/_site/images/phaser-logo.png deleted file mode 100644 index 3a72d92e8..000000000 Binary files a/examples/_site/images/phaser-logo.png and /dev/null differ diff --git a/examples/_site/images/phaser-version.png b/examples/_site/images/phaser-version.png deleted file mode 100644 index 5839174bf..000000000 Binary files a/examples/_site/images/phaser-version.png and /dev/null differ diff --git a/examples/_site/images/photonstorm-logo.png b/examples/_site/images/photonstorm-logo.png deleted file mode 100644 index 75ae525bf..000000000 Binary files a/examples/_site/images/photonstorm-logo.png and /dev/null differ diff --git a/examples/_site/images/prize-bg.png b/examples/_site/images/prize-bg.png deleted file mode 100644 index f6215e7d7..000000000 Binary files a/examples/_site/images/prize-bg.png and /dev/null differ diff --git a/examples/_site/images/prize-button.png b/examples/_site/images/prize-button.png deleted file mode 100644 index b70eaec3b..000000000 Binary files a/examples/_site/images/prize-button.png and /dev/null differ diff --git a/examples/_site/images/reset-button.png b/examples/_site/images/reset-button.png deleted file mode 100644 index 54f821da4..000000000 Binary files a/examples/_site/images/reset-button.png and /dev/null differ diff --git a/examples/_site/images/right-label.png b/examples/_site/images/right-label.png deleted file mode 100644 index 1163d1970..000000000 Binary files a/examples/_site/images/right-label.png and /dev/null differ diff --git a/examples/_site/images/space-label.png b/examples/_site/images/space-label.png deleted file mode 100644 index 073632ec9..000000000 Binary files a/examples/_site/images/space-label.png and /dev/null differ diff --git a/examples/_site/images/twitter-icon.png b/examples/_site/images/twitter-icon.png deleted file mode 100644 index 3d7a57c3b..000000000 Binary files a/examples/_site/images/twitter-icon.png and /dev/null differ diff --git a/examples/_site/images/up-label.png b/examples/_site/images/up-label.png deleted file mode 100644 index 1df6f0424..000000000 Binary files a/examples/_site/images/up-label.png and /dev/null differ diff --git a/examples/_site/images/version-button.png b/examples/_site/images/version-button.png deleted file mode 100644 index 4017049a5..000000000 Binary files a/examples/_site/images/version-button.png and /dev/null differ diff --git a/examples/_site/js/gamecontroller.js b/examples/_site/js/gamecontroller.js deleted file mode 100644 index 71efec2c6..000000000 --- a/examples/_site/js/gamecontroller.js +++ /dev/null @@ -1,1315 +0,0 @@ -/* HTML5 Virtual Game Controller - * Courtesy of Austin Hallock - * https://github.com/austinhallock/html5-virtual-game-controller/ - * Copyright (c) 2013 Clay.io - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -/** - * Helpers - */ -( function(exports) { - var __slice = [].slice; - var __hasProp = {}.hasOwnProperty; - var __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; - /* $.extend functionality */ - function extend( target, src ) - { - var options, name, copy, copyIsArray, clone, - i = 1, - length = 2, - deep = true; - - // Handle a deep copy situation - if( typeof target === "boolean" ) - { - deep = target; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something( possible in deep copy ) - if( typeof target !== "object" && !typeof target === 'function' ) - { - target = {}; - } - // Only deal with non-null/undefined values - if( options = src ) - { - // Extend the base object - for( name in options ) - { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if( target === copy ) - { - continue; - } - // Recurse if we're merging plain objects or arrays - if( deep &&( typeof copy == 'object' ||( copyIsArray = Object.prototype.toString.call( copy ) === '[object Array]' ) ) ) - { - if( copyIsArray ) - { - copyIsArray = false; - clone = src && Object.prototype.toString.call( src ) === '[object Array]' ? src : []; - - } - else - { - clone = src && typeof src == 'object' ? src : {}; - } - // Never move original objects, clone them - target[name] = extend( clone, copy ); - - // Don't bring in undefined values - } - else if( typeof copy !== 'undefined' ) - { - target[name] = copy; - } - } - } - return target; - } - - // Make available to window - exports.GameController = { - - // Default options, - options: { - left: { - type: 'dpad', - position: { left: '13%', bottom: '22%' }, - dpad: { - up: { - width: '7%', - height: '15%', - stroke: 2, - touchStart: function() { - GameController.simulateKeyEvent( 'press', 38 ); - GameController.simulateKeyEvent( 'down', 38 ); - }, - touchEnd: function() { - GameController.simulateKeyEvent( 'up', 38 ); - } - }, - left: { - width: '15%', - height: '7%', - stroke: 2, - touchStart: function() { - GameController.simulateKeyEvent( 'press', 37 ); - GameController.simulateKeyEvent( 'down', 37 ); - }, - touchEnd: function() { - GameController.simulateKeyEvent( 'up', 37 ); - } - }, - down: { - width: '7%', - height: '15%', - stroke: 2, - touchStart: function() { - GameController.simulateKeyEvent( 'press', 40 ); - GameController.simulateKeyEvent( 'down', 40 ); - }, - touchEnd: function() { - GameController.simulateKeyEvent( 'up', 40 ); - } - }, - right: { - width: '15%', - height: '7%', - stroke: 2, - touchStart: function() { - GameController.simulateKeyEvent( 'press', 39 ); - GameController.simulateKeyEvent( 'down', 39 ); - }, - touchEnd: function() { - GameController.simulateKeyEvent( 'up', 39 ); - } - } - }, - joystick: { - radius: 60, - touchMove: function( e ) { - console.log( e ); - } - } - }, - right: { - type: 'buttons', - position: { right: '17%', bottom: '28%' }, - buttons: [ - { offset: { x: '-13%', y: 0 }, label: 'X', radius: '7%', stroke: 2, backgroundColor: 'blue', fontColor: '#fff', touchStart: function() { - // Blue is currently mapped to up button - GameController.simulateKeyEvent( 'press', 88 ); // x key - GameController.simulateKeyEvent( 'down', 88 ); - }, touchEnd: function() { - GameController.simulateKeyEvent( 'up', 88 ); - } }, - { offset: { x: 0, y: '-11%' }, label: 'Y', radius: '7%', stroke: 2, backgroundColor: 'yellow', fontColor: '#fff', touchStart: function() { - GameController.simulateKeyEvent( 'press', 70 ); // f key - GameController.simulateKeyEvent( 'down', 70 ); - }, touchEnd: function() { - GameController.simulateKeyEvent( 'up', 70 ); - } }, - { offset: { x: '13%', y: 0 }, label: 'B', radius: '7%', stroke: 2, backgroundColor: 'red', fontColor: '#fff', touchStart: function() { - GameController.simulateKeyEvent( 'press', 90 ); // z key - GameController.simulateKeyEvent( 'down', 90 ); - }, touchEnd: function() { - GameController.simulateKeyEvent( 'up', 90 ); - } }, - { offset: { x: 0, y: '11%' }, label: 'A', radius: '7%', stroke: 2, backgroundColor: 'green', fontColor: '#fff', touchStart: function() { - GameController.simulateKeyEvent( 'press', 67 ); // a key - GameController.simulateKeyEvent( 'down', 67 ); - }, touchEnd: function() { - GameController.simulateKeyEvent( 'up', 67 ); - } } - ], - dpad: { - up: { - width: '7%', - height: '15%', - stroke: 2 - }, - left: { - width: '15%', - height: '7%', - stroke: 2 - }, - down: { - width: '7%', - height: '15%', - stroke: 2 - }, - right: { - width: '15%', - height: '7%', - stroke: 2 - } - }, - joystick: { - radius: 60, - touchMove: function( e ) { - console.log( e ); - } - } - }, - touchRadius: 45 - }, - - // Areas (objects) on the screen that can be touched - touchableAreas: [], - touchableAreasCount: 0, - - // Multi-touch - touches: [], - - // Canvas offset on page (for coverting touch coordinates) - offsetX: 0, - offsetY: 0, - - // Bounding box - used for clearRect - first we determine which areas of the canvas are actually drawn to - bound: { - left: false, - right: false, - top: false, - bottom: false - }, - - // Heavy sprites (with gradients) are cached as a canvas to improve performance - cachedSprites: {}, - - paused: false, - - init: function( options ) { - - // Don't do anything if there's no touch support - if( ! 'ontouchstart' in document.documentElement ) - return; - - - // Merge default options and specified options - options = options || {}; - extend( this.options, options ); - - var userAgent = navigator.userAgent.toLowerCase(); - // See if we should run the performanceFriendly version (for slower CPUs) - this.performanceFriendly = ( userAgent.indexOf( 'iphone' ) !== -1 || userAgent.indexOf( 'android' ) !== -1 || this.options.forcePerformanceFriendly ); - - // Grab the canvas if one wasn't passed - var ele; - if( !this.options.canvas || !( ele = document.getElementById( this.options.canvas ) ) ) - { - this.options.canvas = document.getElementsByTagName( 'canvas' )[0]; - } - else if( ele ) - { - this.options.canvas = ele; - } - - this.options.ctx = this.options.canvas.getContext( '2d' ); - - // Create a canvas that goes directly on top of the game canvas - this.createOverlayCanvas(); - }, - - /** - * Finds the actual 4 corners of canvas that are being used (so we don't have to clear the entire canvas each render) - * Called when each new touchableArea is added in - * @param {object} options - x, y, width, height - */ - boundingSet: function( options ) { - var directions = ['left', 'right']; - - // Square - pivot is top left - if( options.width ) - { - var width = this.getPixels( options.width ); - var height = this.getPixels( options.height ); - var left = this.getPixels( options.x ); - var top = this.getPixels( options.y ); - } - // Circle - pivot is center - else - { - if( this.options.touchRadius ) - var radius = this.getPixels( options.radius ) * 2 + ( this.getPixels( this.options.touchRadius ) / 2 ); // size of the box the joystick can go to - else - var radius = options.radius; - var width = height = ( radius + this.getPixels( options.stroke ) ) * 2; - var left = this.getPixels( options.x ) - ( width / 2 ); - var top = this.getPixels( options.y ) - ( height / 2 ); - } - var right = left + width; - var bottom = top + height; - - if( this.bound.left === false || left < this.bound.left ) - this.bound.left = left; - if( this.bound.right === false || right > this.bound.right ) - this.bound.right = right; - if( this.bound.top === false || top < this.bound.top ) - this.bound.top = top; - if( this.bound.bottom === false || bottom > this.bound.bottom ) - this.bound.bottom = bottom; - }, - - /** - * Creates the canvas that sits on top of the game's canvas and holds game controls - */ - createOverlayCanvas: function() { - this.canvas = document.createElement( 'canvas' ); - - // Scale to same size as original canvas - this.resize( true ); - - document.getElementsByTagName( 'body' )[0].appendChild( this.canvas ); - this.ctx = this.canvas.getContext( '2d' ); - - var _this = this; - window.addEventListener( 'resize', function() { - // Wait for any other events to finish - setTimeout( function() { GameController.resize.call( _this ); }, 1 ); - } ); - - - // Set the touch events for this new canvas - this.setTouchEvents(); - - // Load in the initial UI elements - this.loadSide( 'left' ); - this.loadSide( 'right' ); - - // Starts up the rendering / drawing - this.render(); - - if( ! this.touches || this.touches.length == 0 ) - this.paused = true; // pause until a touch event - }, - - pixelRatio: 1, - resize: function( firstTime ) { - // Scale to same size as original canvas - this.canvas.width = this.options.canvas.width; - this.canvas.height = this.options.canvas.height; - - this.offsetX = GameController.options.canvas.offsetLeft + document.body.scrollLeft; - this.offsetY = GameController.options.canvas.offsetTop + document.body.scrollTop; - - // Get in on this retina action - if( this.options.canvas.style.width && this.options.canvas.style.height && this.options.canvas.style.height.indexOf( 'px' ) !== -1 ) - { - this.canvas.style.width = this.options.canvas.style.width; - this.canvas.style.height = this.options.canvas.style.height; - this.pixelRatio = this.canvas.width / parseInt( this.canvas.style.width ); - } - - this.canvas.style.position = 'absolute'; - this.canvas.style.zIndex = '5'; - this.canvas.style.left = this.options.canvas.offsetLeft + 'px'; - this.canvas.style.top = this.options.canvas.offsetTop + 'px'; - this.canvas.setAttribute( 'style', this.canvas.getAttribute( 'style' ) +' -ms-touch-action: none;' ); - - if( !firstTime ) - { - // Remove all current buttons - this.touchableAreas = []; - // Clear out the cached sprites - this.cachedSprites = []; - // Reload in the initial UI elements - this.reloadSide( 'left' ); - this.reloadSide( 'right' ); - } - }, - - /** - * Returns the scaled pixels. Given the value passed - * @param {int/string} value - either an integer for # of pixels, or 'x%' for relative - * @param {char} axis - x, y - */ - getPixels: function( value, axis ) - { - if( typeof value === 'undefined' ) - return 0 - else if( typeof value === 'number' ) - return value; - else // a percentage - { - if( axis == 'x' ) - return ( parseInt( value ) / 100 ) * this.canvas.width; - else - return ( parseInt( value ) / 100 ) * this.canvas.height; - } - }, - - /** - * Simulates a key press - * @param {string} eventName - 'down', 'up' - * @param {char} character - */ - simulateKeyEvent: function( eventName, keyCode ) { - if( typeof window.onkeydown === 'undefined' ) // No keyboard, can't simulate... - return false; - - /* If they have jQuery, use it because it works better for mobile safari */ - if( typeof jQuery !== 'undefined' ) - { - var press = jQuery.Event( 'key' + eventName ); - press.ctrlKey = false; - press.which = keyCode; - press.keyCode = keyCode; - // Keypress on just the canvas instead of the document - $( this.options.canvas ).trigger( press ); - return; - } - - var oEvent = document.createEvent( 'KeyboardEvent' ); - - // Chromium Hack - if( navigator.userAgent.toLowerCase().indexOf( 'chrome' ) !== -1 ) - { - Object.defineProperty( oEvent, 'keyCode', { - get : function() { - return this.keyCodeVal; - } - } ); - Object.defineProperty( oEvent, 'which', { - get : function() { - return this.keyCodeVal; - } - } ); - } - - if( oEvent.initKeyboardEvent ) - { - oEvent.initKeyboardEvent( 'key' + eventName, true, true, document.defaultView, false, false, false, false, keyCode, keyCode ); - } - else - { - oEvent.initKeyEvent( 'key' + eventName, true, true, document.defaultView, false, false, false, false, keyCode, keyCode ); - } - - oEvent.keyCodeVal = keyCode; - - }, - - setTouchEvents: function() { - var _this = this; - var touchStart = function( e ) { - if( _this.paused ) - { - _this.paused = false; - } - - e.preventDefault(); - - // Microsoft always has to have their own stuff... - if( window.navigator.msPointerEnabled && e.clientX && e.pointerType == e.MSPOINTER_TYPE_TOUCH ) - { - _this.touches[ e.pointerId ] = { clientX: e.clientX, clientY: e.clientY }; - } - else - { - _this.touches = e.touches || []; - } - }; - - this.canvas.addEventListener( 'touchstart', touchStart, false ); - - var touchEnd = function( e ) { - e.preventDefault(); - - if( window.navigator.msPointerEnabled && e.pointerType == e.MSPOINTER_TYPE_TOUCH ) - { - delete _this.touches[ e.pointerId ]; - } - else - { - _this.touches = e.touches || []; - } - - if( !e.touches || e.touches.length == 0 ) - { - // Draw once more to remove the touch area - _this.render(); - _this.paused = true; - } - }; - this.canvas.addEventListener( 'touchend', touchEnd ); - - var touchMove = function( e ) { - e.preventDefault(); - - if( window.navigator.msPointerEnabled && e.clientX && e.pointerType == e.MSPOINTER_TYPE_TOUCH ) - { - _this.touches[ e.pointerId ] = { clientX: e.clientX, clientY: e.clientY }; - } - else - { - _this.touches = e.touches || []; - } - }; - this.canvas.addEventListener( 'touchmove', touchMove ); - - if( window.navigator.msPointerEnabled ) - { - this.canvas.addEventListener( 'MSPointerDown', touchStart ); - this.canvas.addEventListener( 'MSPointerUp', touchEnd ); - this.canvas.addEventListener( 'MSPointerMove', touchMove ); - } - }, - - /** - * Adds the area to a list of touchable areas, draws - * @param {object} options with properties: x, y, width, height, touchStart, touchEnd, touchMove - */ - addTouchableDirection: function( options ) { - - var direction = new TouchableDirection( options ); - - direction.id = this.touchableAreas.push( direction ); - this.touchableAreasCount++; - - this.boundingSet( options ); - }, - - /** - * Adds the circular area to a list of touchable areas, draws - * @param {object} options with properties: x, y, width, height, touchStart, touchEnd, touchMove - */ - addJoystick: function( options ) { //x, y, radius, backgroundColor, touchStart, touchEnd ) { - - var joystick = new TouchableJoystick( options ); - - joystick.id = this.touchableAreas.push( joystick ); - this.touchableAreasCount++; - - this.boundingSet( options ); - }, - - /** - * Adds the circular area to a list of touchable areas, draws - * @param {object} options with properties: x, y, width, height, touchStart, touchEnd, touchMove - */ - addButton: function( options ) { //x, y, radius, backgroundColor, touchStart, touchEnd ) { - - var button = new TouchableButton( options ); - - button.id = this.touchableAreas.push( button ); - this.touchableAreasCount++; - - this.boundingSet( options ); - }, - - addTouchableArea: function( check, callback ) { - }, - - loadButtons: function( side ) { - var buttons = this.options[ side ].buttons; - var _this = this; - for( var i = 0, j = buttons.length; i < j; i++ ) - { - if( typeof buttons[i] === 'undefined' || typeof buttons[i].offset === 'undefined' ) - continue; - - var posX = this.getPositionX( side ); - var posY = this.getPositionY( side ); - - buttons[i].x = posX + this.getPixels( buttons[i].offset.x, 'y' ); - buttons[i].y = posY + this.getPixels( buttons[i].offset.y, 'y' ); - - this.addButton( buttons[i] ); - } - }, - - loadDPad: function( side ) { - var dpad = this.options[ side ].dpad || {}; - - // Centered value is at this.options[ side ].position - - var _this = this; - - var posX = this.getPositionX( side ); - var posY = this.getPositionY( side ); - - - // If they have all 4 directions, add a circle to the center for looks - if( dpad.up && dpad.left && dpad.down && dpad.right ) - { - var options = { - x: posX, - y: posY, - radius: dpad.right.height - } - var center = new TouchableCircle( options ); - this.touchableAreas.push( center ); - this.touchableAreasCount++; - } - - // Up arrow - if( dpad.up !== false ) - { - dpad.up.x = posX - this.getPixels( dpad.up.width, 'y' ) / 2; - dpad.up.y = posY - ( this.getPixels( dpad.up.height, 'y' ) + this.getPixels( dpad.left.height, 'y' ) / 2 ); - dpad.up.direction = 'up'; - this.addTouchableDirection( dpad.up ); - } - - // Left arrow - if( dpad.left !== false ) - { - dpad.left.x = posX - ( this.getPixels( dpad.left.width, 'y' ) + this.getPixels( dpad.up.width, 'y' ) / 2 ); - dpad.left.y = posY - ( this.getPixels( dpad.left.height, 'y' ) / 2 ); - dpad.left.direction = 'left'; - this.addTouchableDirection( dpad.left ); - } - - // Down arrow - if( dpad.down !== false ) - { - dpad.down.x = posX - this.getPixels( dpad.down.width, 'y' ) / 2; - dpad.down.y = posY + ( this.getPixels( dpad.left.height, 'y' ) / 2 ); - dpad.down.direction = 'down'; - this.addTouchableDirection( dpad.down ); - } - - // Right arrow - if( dpad.right !== false ) - { - dpad.right.x = posX + ( this.getPixels( dpad.up.width, 'y' ) / 2 ); - dpad.right.y = posY - this.getPixels( dpad.right.height, 'y' ) / 2; - dpad.right.direction = 'right'; - this.addTouchableDirection( dpad.right ); - } - - }, - - loadJoystick: function( side ) { - var joystick = this.options[ side ].joystick; - joystick.x = this.getPositionX( side ); - joystick.y = this.getPositionY( side ); - - this.addJoystick( joystick ); - }, - - /** - * Used for resizing. Currently is just an alias for loadSide - */ - reloadSide: function( side ) { - // Load in new ones - this.loadSide( side ); - }, - - loadSide: function( side ) { - if( this.options[ side ].type === 'dpad' ) - { - this.loadDPad( side ); - } - else if( this.options[ side ].type === 'joystick' ) - { - this.loadJoystick( side ); - } - else if( this.options[ side ].type === 'buttons' ) - { - this.loadButtons( side ); - } - }, - - /** - * Normalize touch positions by the left and top offsets - * @param {int} x - */ - normalizeTouchPositionX: function( x ) - { - return ( x - this.offsetX ) * ( this.pixelRatio ); - }, - - /** - * Normalize touch positions by the left and top offsets - * @param {int} y - */ - normalizeTouchPositionY: function( y ) - { - return ( y - this.offsetY ) * ( this.pixelRatio ); - }, - - /** - * Returns the x position when given # of pixels from right (based on canvas size) - * @param {int} right - */ - getXFromRight: function( right ) { - return this.canvas.width - right; - }, - - - /** - * Returns the y position when given # of pixels from bottom (based on canvas size) - * @param {int} right - */ - getYFromBottom: function( bottom ) { - return this.canvas.height - bottom; - }, - - /** - * Grabs the x position of either the left or right side/controls - * @param {string} side - 'left', 'right' - */ - getPositionX: function( side ) { - if( typeof this.options[ side ].position.left !== 'undefined' ) - return this.getPixels( this.options[ side ].position.left, 'x' ); - else - return this.getXFromRight( this.getPixels( this.options[ side ].position.right, 'x' ) ); - }, - - /** - * Grabs the y position of either the left or right side/controls - * @param {string} side - 'left', 'right' - */ - getPositionY: function( side ) { - if( typeof this.options[ side ].position.top !== 'undefined' ) - return this.getPixels( this.options[ side ].position.top, 'y' ); - else - return this.getYFromBottom( this.getPixels( this.options[ side ].position.bottom, 'y' ) ); - }, - - /** - * Processes the info for each touchableArea - */ - renderAreas: function() { - for( var i = 0, j = this.touchableAreasCount; i < j; i++ ) - { - var area = this.touchableAreas[ i ]; - - if( typeof area === 'undefined' ) - continue; - - area.draw(); - - // Go through all touches to see if any hit this area - var touched = false; - for( var k = 0, l = this.touches.length; k < l; k++ ) - { - var touch = this.touches[ k ]; - if( typeof touch === 'undefined' ) - continue; - - var x = this.normalizeTouchPositionX( touch.clientX ), y = this.normalizeTouchPositionY( touch.clientY ); - - // Check that it's in the bounding box/circle - if( ( area.check( x, y ) ) !== false ) - { - if( !touched ) - touched = this.touches[ k ]; - } - } - - if( touched ) - { - if( !area.active ) - area.touchStartWrapper( touched ); - area.touchMoveWrapper( touched ); - } - else if( area.active ) - { - area.touchEndWrapper( touched ); - } - } - }, - - render: function() { - if( ! this.paused || ! this.performanceFriendly ) - this.ctx.clearRect( this.bound.left, this.bound.top, this.bound.right - this.bound.left, this.bound.bottom - this.bound.top ); - - // Draw feedback for when screen is being touched - // When no touch events are happening, this enables 'paused' mode, which skips running this - // This isn't run at all in performanceFriendly mode - if( ! this.paused && ! this.performanceFriendly ) - { - var cacheId = 'touch-circle'; - var cached = this.cachedSprites[ cacheId ]; - - if( ! cached && this.options.touchRadius ) - { - var subCanvas = document.createElement( 'canvas' ); - var ctx = subCanvas.getContext( '2d' ); - subCanvas.width = 2 * this.options.touchRadius; - subCanvas.height = 2 * this.options.touchRadius; - - var center = this.options.touchRadius; - var gradient = ctx.createRadialGradient( center, center, 1, center, center, this.options.touchRadius ); // 10 = end radius - gradient.addColorStop( 0, 'rgba( 200, 200, 200, 1 )' ); - gradient.addColorStop( 1, 'rgba( 200, 200, 200, 0 )' ); - ctx.beginPath(); - ctx.fillStyle = gradient; - ctx.arc( center, center, this.options.touchRadius, 0 , 2 * Math.PI, false ); - ctx.fill(); - - cached = GameController.cachedSprites[ cacheId ] = subCanvas; - } - // Draw the current touch positions if any - for( var i = 0, j = this.touches.length; i < j; i++ ) - { - var touch = this.touches[ i ]; - if( typeof touch === 'undefined' ) - continue; - var x = this.normalizeTouchPositionX( touch.clientX ), y = this.normalizeTouchPositionY( touch.clientY ); - if( x - this.options.touchRadius > this.bound.left && x + this.options.touchRadius < this.bound.right && - y - this.options.touchRadius > this.bound.top && y + this.options.touchRadius < this.bound.bottom ) - this.ctx.drawImage( cached, x - this.options.touchRadius, y - this.options.touchRadius ); - } - } - - // Render if the game isn't paused, or we're not in performanceFriendly mode (running when not paused keeps the semi-transparent gradients looking better for some reason) - if( ! this.paused || ! this.performanceFriendly ) - { - // Process all the info for each touchable area - this.renderAreas(); - } - - window.requestAnimationFrame( this.renderWrapper ); - }, - /** - * So we can keep scope, and don't have to create a new obj every requestAnimationFrame (bad for garbage collection) - */ - renderWrapper: function() { - GameController.render(); - }, - } - - /** - * Superclass for touchable stuff - */ - var TouchableArea = ( function() { - - function TouchableArea() - { - } - - // Called when this direction is being touched - TouchableArea.prototype.touchStart = null; - - // Called when this direction is being moved - TouchableArea.prototype.touchMove = null; - - // Called when this direction is no longer being touched - TouchableArea.prototype.touchEnd = null; - - TouchableArea.prototype.type = 'area'; - TouchableArea.prototype.id = false; - TouchableArea.prototype.active = false; - - /** - * Sets the user-specified callback for this direction being touched - * @param {function} callback - */ - TouchableArea.prototype.setTouchStart = function( callback ) { - this.touchStart = callback; - }; - - /** - * Called when this direction is no longer touched - */ - TouchableArea.prototype.touchStartWrapper = function( e ) { - // Fire the user specified callback - if( this.touchStart ) - this.touchStart(); - - // Mark this direction as active - this.active = true; - }; - - /** - * Sets the user-specified callback for this direction no longer being touched - * @param {function} callback - */ - TouchableArea.prototype.setTouchMove = function( callback ) { - this.touchMove = callback; - }; - - /** - * Called when this direction is moved. Make sure it's actually changed before passing to developer - */ - TouchableArea.prototype.lastPosX = 0; - TouchableArea.prototype.lastPosY = 0; - TouchableArea.prototype.touchMoveWrapper = function( e ) { - // Fire the user specified callback - if( this.touchMove && ( e.clientX != TouchableArea.prototype.lastPosX || e.clientY != TouchableArea.prototype.lastPosY ) ) - { - this.touchMove(); - this.lastPosX = e.clientX; - this.lastPosY = e.clientY; - } - // Mark this direction as active - this.active = true; - }; - - /** - * Sets the user-specified callback for this direction no longer being touched - * @param {function} callback - */ - TouchableArea.prototype.setTouchEnd = function( callback ) { - this.touchEnd = callback; - }; - - /** - * Called when this direction is first touched - */ - TouchableArea.prototype.touchEndWrapper = function( e ) { - // Fire the user specified callback - if( this.touchEnd ) - this.touchEnd(); - - // Mark this direction as inactive - this.active = false; - - GameController.render(); - }; - - return TouchableArea; - - } )(); - - var TouchableDirection = ( function( __super ) { - __extends( TouchableDirection, __super ); - - function TouchableDirection( options ) - { - for( var i in options ) - { - if( i == 'x' ) - this[i] = GameController.getPixels( options[i], 'x' ); - else if( i == 'y' || i == 'height' || i == 'width' ) - this[i] = GameController.getPixels( options[i], 'y' ); - else - this[i] = options[i]; - } - - this.draw(); - } - - TouchableDirection.prototype.type = 'direction'; - - /** - * Checks if the touch is within the bounds of this direction - */ - TouchableDirection.prototype.check = function( touchX, touchY ) { - var distanceX, distanceY; - if( ( Math.abs( touchX - this.x ) < ( GameController.options.touchRadius / 2 ) || ( touchX > this.x ) ) && // left - ( Math.abs( touchX - ( this.x + this.width ) ) < ( GameController.options.touchRadius / 2 ) || ( touchX < this.x + this.width ) ) && // right - ( Math.abs( touchY - this.y ) < ( GameController.options.touchRadius / 2 ) || ( touchY > this.y ) ) && // top - ( Math.abs( touchY - ( this.y + this.height ) ) < ( GameController.options.touchRadius / 2 ) || ( touchY < this.y + this.height ) ) // bottom - ) - return true; - - return false; - }; - - TouchableDirection.prototype.draw = function() { - var cacheId = this.type + '' + this.id + '' + this.active; - var cached = GameController.cachedSprites[ cacheId ]; - if( ! cached ) - { - var subCanvas = document.createElement( 'canvas' ); - var ctx = subCanvas.getContext( '2d' ); - subCanvas.width = this.width + 2 * this.stroke; - subCanvas.height = this.height + 2 * this.stroke; - - var opacity = this.opacity || 0.9; - - if( ! this.active ) // Direction currently being touched - opacity *= 0.5; - - switch( this.direction ) - { - case 'up': - var gradient = ctx.createLinearGradient( 0, 0, 0, this.height ); - gradient.addColorStop( 0, 'rgba( 0, 0, 0, ' + ( opacity * 0.5 ) + ' )' ); - gradient.addColorStop( 1, 'rgba( 0, 0, 0, ' + opacity + ' )' ); - break; - case 'left': - var gradient = ctx.createLinearGradient( 0, 0, this.width, 0 ); - gradient.addColorStop( 0, 'rgba( 0, 0, 0, ' + ( opacity * 0.5 ) + ' )' ); - gradient.addColorStop( 1, 'rgba( 0, 0, 0, ' + opacity + ' )' ); - break; - case 'right': - var gradient = ctx.createLinearGradient( 0, 0, this.width, 0 ); - gradient.addColorStop( 0, 'rgba( 0, 0, 0, ' + opacity + ' )' ); - gradient.addColorStop( 1, 'rgba( 0, 0, 0, ' + ( opacity * 0.5 ) + ' )' ); - break; - case 'down': - default: - var gradient = ctx.createLinearGradient( 0, 0, 0, this.height ); - gradient.addColorStop( 0, 'rgba( 0, 0, 0, ' + opacity + ' )' ); - gradient.addColorStop( 1, 'rgba( 0, 0, 0, ' + ( opacity * 0.5 ) + ' )' ); - } - ctx.fillStyle = gradient; - - ctx.fillRect( 0, 0, this.width, this.height ); - ctx.lineWidth = this.stroke; - ctx.strokeStyle = 'rgba( 255, 255, 255, 0.1 )'; - ctx.strokeRect( 0, 0, this.width, this.height ); - - cached = GameController.cachedSprites[ cacheId ] = subCanvas; - } - - GameController.ctx.drawImage( cached, this.x, this.y ); - - - }; - - return TouchableDirection; - } )( TouchableArea ); - - var TouchableButton = ( function( __super ) { - __extends( TouchableButton, __super ); - - function TouchableButton( options ) //x, y, radius, backgroundColor ) - { - for( var i in options ) - { - if( i == 'x' ) - this[i] = GameController.getPixels( options[i], 'x' ); - else if( i == 'x' || i == 'radius' ) - this[i] = GameController.getPixels( options[i], 'y' ); - else - this[i] = options[i]; - } - - this.draw(); - } - - TouchableButton.prototype.type = 'button'; - - /** - * Checks if the touch is within the bounds of this direction - */ - TouchableButton.prototype.check = function( touchX, touchY ) { - if( - ( Math.abs( touchX - this.x ) < this.radius + ( GameController.options.touchRadius / 2 ) ) && - ( Math.abs( touchY - this.y ) < this.radius + ( GameController.options.touchRadius / 2 ) ) - ) - return true; - - return false; - }; - - TouchableButton.prototype.draw = function() { - var cacheId = this.type + '' + this.id + '' + this.active; - var cached = GameController.cachedSprites[ cacheId ]; - if( ! cached ) - { - var subCanvas = document.createElement( 'canvas' ); - var ctx = subCanvas.getContext( '2d' ); - ctx.lineWidth = this.stroke; - subCanvas.width = subCanvas.height = 2 * ( this.radius + ctx.lineWidth ); - - - var gradient = ctx.createRadialGradient( this.radius, this.radius, 1, this.radius, this.radius, this.radius ); - var textShadowColor; - switch( this.backgroundColor ) - { - case 'blue': - gradient.addColorStop( 0, 'rgba(123, 181, 197, 0.6)' ); - gradient.addColorStop( 1, '#105a78' ); - textShadowColor = '#0A4861'; - break; - case 'green': - gradient.addColorStop( 0, 'rgba(29, 201, 36, 0.6)' ); - gradient.addColorStop( 1, '#107814' ); - textShadowColor = '#085C0B'; - break; - case 'red': - gradient.addColorStop( 0, 'rgba(165, 34, 34, 0.6)' ); - gradient.addColorStop( 1, '#520101' ); - textShadowColor = '#330000'; - break; - case 'yellow': - gradient.addColorStop( 0, 'rgba(219, 217, 59, 0.6)' ); - gradient.addColorStop( 1, '#E8E10E' ); - textShadowColor = '#BDB600'; - break; - case 'white': - default: - gradient.addColorStop( 0, 'rgba( 255,255,255,.3 )' ); - gradient.addColorStop( 1, '#eee' ); - break; - } - - if( this.active ) - ctx.fillStyle = textShadowColor; - else - ctx.fillStyle = gradient; - - ctx.strokeStyle = textShadowColor; - - ctx.beginPath(); - //ctx.arc( this.x, this.y, this.radius, 0 , 2 * Math.PI, false ); - ctx.arc( subCanvas.width / 2, subCanvas.width / 2, this.radius, 0 , 2 * Math.PI, false ); - ctx.fill(); - ctx.stroke(); - - if( this.label ) - { - // Text Shadow - ctx.fillStyle = textShadowColor; - ctx.font = 'bold ' + ( this.fontSize || subCanvas.height * 0.35 ) + 'px Verdana'; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - ctx.fillText( this.label, subCanvas.height / 2 + 2, subCanvas.height / 2 + 2 ); - - - ctx.fillStyle = this.fontColor; - ctx.font = 'bold ' + ( this.fontSize || subCanvas.height * 0.35 ) + 'px Verdana'; - ctx.textAlign = 'center'; - ctx.textBaseline = 'middle'; - ctx.fillText( this.label, subCanvas.height / 2, subCanvas.height / 2 ); - } - - cached = GameController.cachedSprites[ cacheId ] = subCanvas; - } - - GameController.ctx.drawImage( cached, this.x, this.y ); - - - }; - - return TouchableButton; - } )( TouchableArea ); - - var TouchableJoystick = ( function( __super ) { - __extends( TouchableJoystick, __super ); - - function TouchableJoystick( options ) //x, y, radius, backgroundColor ) - { - for( var i in options ) - this[i] = options[i]; - - this.currentX = this.currentX || this.x; - this.currentY = this.currentY || this.y; - } - - TouchableJoystick.prototype.type = 'joystick'; - - /** - * Checks if the touch is within the bounds of this direction - */ - TouchableJoystick.prototype.check = function( touchX, touchY ) { - if( - ( Math.abs( touchX - this.x ) < this.radius + ( GameController.getPixels( GameController.options.touchRadius ) / 2 ) ) && - ( Math.abs( touchY - this.y ) < this.radius + ( GameController.getPixels( GameController.options.touchRadius ) / 2 ) ) - ) - return true; - - return false; - }; - - /** - * details for the joystick move event, stored here so we're not constantly creating new objs for garbage. The object has params: - * dx - the number of pixels the current joystick center is from the base center in x direction - * dy - the number of pixels the current joystick center is from the base center in y direction - * max - the maximum number of pixels dx or dy can be - * normalizedX - a number between -1 and 1 relating to how far left or right the joystick is - * normalizedY - a number between -1 and 1 relating to how far up or down the joystick is - */ - TouchableJoystick.prototype.moveDetails = {}; - - /** - * Called when this joystick is moved - */ - TouchableJoystick.prototype.touchMoveWrapper = function( e ) { - this.currentX = GameController.normalizeTouchPositionX( e.clientX ); - this.currentY = GameController.normalizeTouchPositionY( e.clientY ); - - // Fire the user specified callback - if( this.touchMove ) - { - if( this.moveDetails.dx != this.currentX - this.x && this.moveDetails.dy != this.y - this.currentY ) - { - this.moveDetails.dx = this.currentX - this.x; // reverse so right is positive - this.moveDetails.dy = this.y - this.currentY; - this.moveDetails.max = this.radius + ( GameController.options.touchRadius / 2 ); - this.moveDetails.normalizedX = this.moveDetails.dx / this.moveDetails.max; - this.moveDetails.normalizedY = this.moveDetails.dy / this.moveDetails.max; - - this.touchMove( this.moveDetails ); - } - } - - - // Mark this direction as inactive - this.active = true; - }; - - TouchableJoystick.prototype.draw = function() { - if( ! this.id ) // wait until id is set - return false; - - var cacheId = this.type + '' + this.id + '' + this.active; - var cached = GameController.cachedSprites[ cacheId ]; - if( ! cached ) - { - var subCanvas = document.createElement( 'canvas' ); - this.stroke = this.stroke || 2; - subCanvas.width = subCanvas.height = 2 * ( this.radius + ( GameController.options.touchRadius ) + this.stroke ); - - var ctx = subCanvas.getContext( '2d' ); - ctx.lineWidth = this.stroke; - if( this.active ) // Direction currently being touched - { - var gradient = ctx.createRadialGradient( 0, 0, 1, 0, 0, this.radius ); - gradient.addColorStop( 0, 'rgba( 200,200,200,.5 )' ); - gradient.addColorStop( 1, 'rgba( 200,200,200,.9 )' ); - ctx.strokeStyle = '#000'; - } - else - { - // STYLING FOR BUTTONS - var gradient = ctx.createRadialGradient( 0, 0, 1, 0, 0, this.radius ); - gradient.addColorStop( 0, 'rgba( 200,200,200,.2 )' ); - gradient.addColorStop( 1, 'rgba( 200,200,200,.4 )' ); - ctx.strokeStyle = 'rgba( 0,0,0,.4 )'; - } - ctx.fillStyle = gradient; - // Actual joystick part that is being moved - ctx.beginPath(); - ctx.arc( this.radius, this.radius, this.radius, 0 , 2 * Math.PI, false ); - ctx.fill(); - ctx.stroke(); - - cached = GameController.cachedSprites[ cacheId ] = subCanvas; - } - - // Draw the base that stays static - GameController.ctx.fillStyle = '#444'; - GameController.ctx.beginPath(); - GameController.ctx.arc( this.x, this.y, this.radius * 0.7, 0 , 2 * Math.PI, false ); - GameController.ctx.fill(); - GameController.ctx.stroke(); - - GameController.ctx.drawImage( cached, this.currentX - this.radius, this.currentY - this.radius ); - - - }; - - return TouchableJoystick; - } )( TouchableArea ); - - - var TouchableCircle = ( function( __super ) { - __extends( TouchableCircle, __super ); - - function TouchableCircle( options ) - { - for( var i in options ) - { - if( i == 'x' ) - this[i] = GameController.getPixels( options[i], 'x' ); - else if( i == 'x' || i == 'radius' ) - this[i] = GameController.getPixels( options[i], 'y' ); - else - this[i] = options[i]; - } - - this.draw(); - } - - /** - * No touch for this fella - */ - TouchableCircle.prototype.check = function( touchX, touchY ) { - return false; - }; - - TouchableCircle.prototype.draw = function() { - - // STYLING FOR BUTTONS - GameController.ctx.fillStyle = 'rgba( 0, 0, 0, 0.5 )'; - - // Actual joystick part that is being moved - GameController.ctx.beginPath(); - GameController.ctx.arc( this.x, this.y, this.radius, 0 , 2 * Math.PI, false ); - GameController.ctx.fill(); - - }; - - return TouchableCircle; - } )( TouchableArea ); - - /** - * Shim for requestAnimationFrame - */ - ( function() { - if (typeof module !== "undefined") return - var lastTime = 0; - var vendors = ['ms', 'moz', 'webkit', 'o']; - for( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x ) - { - window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; - window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] - || window[vendors[x]+'CancelRequestAnimationFrame']; - } - - if ( !window.requestAnimationFrame ) - window.requestAnimationFrame = function( callback, element ) { - var currTime = new Date().getTime(); - var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); - var id = window.setTimeout( function() { callback(currTime + timeToCall); }, - timeToCall ); - lastTime = currTime + timeToCall; - return id; - }; - - if ( !window.cancelAnimationFrame ) - window.cancelAnimationFrame = function( id ) { - clearTimeout( id ); - }; - }() ); -} )(typeof module !== "undefined" ? module.exports : window) diff --git a/examples/_site/js/jquery-2.0.3.min.js b/examples/_site/js/jquery-2.0.3.min.js deleted file mode 100644 index 2be209dd2..000000000 --- a/examples/_site/js/jquery-2.0.3.min.js +++ /dev/null @@ -1,6 +0,0 @@ -/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license -//@ sourceMappingURL=jquery-2.0.3.min.map -*/ -(function(e,undefined){var t,n,r=typeof undefined,i=e.location,o=e.document,s=o.documentElement,a=e.jQuery,u=e.$,l={},c=[],p="2.0.3",f=c.concat,h=c.push,d=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,x=function(e,n){return new x.fn.init(e,n,t)},b=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^-ms-/,N=/-([\da-z])/gi,E=function(e,t){return t.toUpperCase()},S=function(){o.removeEventListener("DOMContentLoaded",S,!1),e.removeEventListener("load",S,!1),x.ready()};x.fn=x.prototype={jquery:p,constructor:x,init:function(e,t,n){var r,i;if(!e)return this;if("string"==typeof e){if(r="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:T.exec(e),!r||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof x?t[0]:t,x.merge(this,x.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:o,!0)),C.test(r[1])&&x.isPlainObject(t))for(r in t)x.isFunction(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return i=o.getElementById(r[2]),i&&i.parentNode&&(this.length=1,this[0]=i),this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?n.ready(e):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return d.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,t,n,r,i,o,s=arguments[0]||{},a=1,u=arguments.length,l=!1;for("boolean"==typeof s&&(l=s,s=arguments[1]||{},a=2),"object"==typeof s||x.isFunction(s)||(s={}),u===a&&(s=this,--a);u>a;a++)if(null!=(e=arguments[a]))for(t in e)n=s[t],r=e[t],s!==r&&(l&&r&&(x.isPlainObject(r)||(i=x.isArray(r)))?(i?(i=!1,o=n&&x.isArray(n)?n:[]):o=n&&x.isPlainObject(n)?n:{},s[t]=x.extend(l,o,r)):r!==undefined&&(s[t]=r));return s},x.extend({expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=a),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){(e===!0?--x.readyWait:x.isReady)||(x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(o,[x]),x.fn.trigger&&x(o).trigger("ready").off("ready")))},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray,isWindow:function(e){return null!=e&&e===e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if("object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:JSON.parse,parseXML:function(e){var t,n;if(!e||"string"!=typeof e)return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&x.error("Invalid XML: "+e),t},noop:function(){},globalEval:function(e){var t,n=eval;e=x.trim(e),e&&(1===e.indexOf("use strict")?(t=o.createElement("script"),t.text=e,o.head.appendChild(t).parentNode.removeChild(t)):n(e))},camelCase:function(e){return e.replace(k,"ms-").replace(N,E)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,s=j(e);if(n){if(s){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(s){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:function(e){return null==e?"":v.call(e)},makeArray:function(e,t){var n=t||[];return null!=e&&(j(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:g.call(t,e,n)},merge:function(e,t){var n=t.length,r=e.length,i=0;if("number"==typeof n)for(;n>i;i++)e[r++]=t[i];else while(t[i]!==undefined)e[r++]=t[i++];return e.length=r,e},grep:function(e,t,n){var r,i=[],o=0,s=e.length;for(n=!!n;s>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,s=j(e),a=[];if(s)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(a[a.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(a[a.length]=r);return f.apply([],a)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(n=e[t],t=e,e=n),x.isFunction(e)?(r=d.call(arguments,2),i=function(){return e.apply(t||this,r.concat(d.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):undefined},access:function(e,t,n,r,i,o,s){var a=0,u=e.length,l=null==n;if("object"===x.type(n)){i=!0;for(a in n)x.access(e,t,a,n[a],!0,o,s)}else if(r!==undefined&&(i=!0,x.isFunction(r)||(s=!0),l&&(s?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(x(e),n)})),t))for(;u>a;a++)t(e[a],n,s?r:r.call(e[a],a,t(e[a],n)));return i?e:l?t.call(e):u?t(e[0],n):o},now:Date.now,swap:function(e,t,n,r){var i,o,s={};for(o in t)s[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=s[o];return i}}),x.ready.promise=function(t){return n||(n=x.Deferred(),"complete"===o.readyState?setTimeout(x.ready):(o.addEventListener("DOMContentLoaded",S,!1),e.addEventListener("load",S,!1))),n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function j(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}t=x(o),function(e,undefined){var t,n,r,i,o,s,a,u,l,c,p,f,h,d,g,m,y,v="sizzle"+-new Date,b=e.document,w=0,T=0,C=st(),k=st(),N=st(),E=!1,S=function(e,t){return e===t?(E=!0,0):0},j=typeof undefined,D=1<<31,A={}.hasOwnProperty,L=[],q=L.pop,H=L.push,O=L.push,F=L.slice,P=L.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",W="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",$=W.replace("w","w#"),B="\\["+M+"*("+W+")"+M+"*(?:([*^$|!~]?=)"+M+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+$+")|)|)"+M+"*\\]",I=":("+W+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+B.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=RegExp("^"+M+"*,"+M+"*"),X=RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=RegExp(M+"*[+~]"),Y=RegExp("="+M+"*([^\\]'\"]*)"+M+"*\\]","g"),V=RegExp(I),G=RegExp("^"+$+"$"),J={ID:RegExp("^#("+W+")"),CLASS:RegExp("^\\.("+W+")"),TAG:RegExp("^("+W.replace("w","w*")+")"),ATTR:RegExp("^"+B),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:RegExp("^(?:"+R+")$","i"),needsContext:RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Q=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Z=/^(?:input|select|textarea|button)$/i,et=/^h\d$/i,tt=/'|\\/g,nt=RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),rt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{O.apply(L=F.call(b.childNodes),b.childNodes),L[b.childNodes.length].nodeType}catch(it){O={apply:L.length?function(e,t){H.apply(e,F.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function ot(e,t,r,i){var o,s,a,u,l,f,g,m,x,w;if((t?t.ownerDocument||t:b)!==p&&c(t),t=t||p,r=r||[],!e||"string"!=typeof e)return r;if(1!==(u=t.nodeType)&&9!==u)return[];if(h&&!i){if(o=K.exec(e))if(a=o[1]){if(9===u){if(s=t.getElementById(a),!s||!s.parentNode)return r;if(s.id===a)return r.push(s),r}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(a))&&y(t,s)&&s.id===a)return r.push(s),r}else{if(o[2])return O.apply(r,t.getElementsByTagName(e)),r;if((a=o[3])&&n.getElementsByClassName&&t.getElementsByClassName)return O.apply(r,t.getElementsByClassName(a)),r}if(n.qsa&&(!d||!d.test(e))){if(m=g=v,x=t,w=9===u&&e,1===u&&"object"!==t.nodeName.toLowerCase()){f=gt(e),(g=t.getAttribute("id"))?m=g.replace(tt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",l=f.length;while(l--)f[l]=m+mt(f[l]);x=U.test(e)&&t.parentNode||t,w=f.join(",")}if(w)try{return O.apply(r,x.querySelectorAll(w)),r}catch(T){}finally{g||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,r,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>i.cacheLength&&delete t[e.shift()],t[n]=r}return t}function at(e){return e[v]=!0,e}function ut(e){var t=p.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function lt(e,t){var n=e.split("|"),r=e.length;while(r--)i.attrHandle[n[r]]=t}function ct(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return at(function(t){return t=+t,at(function(n,r){var i,o=e([],n.length,t),s=o.length;while(s--)n[i=o[s]]&&(n[i]=!(r[i]=n[i]))})})}s=ot.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},n=ot.support={},c=ot.setDocument=function(e){var t=e?e.ownerDocument||e:b,r=t.defaultView;return t!==p&&9===t.nodeType&&t.documentElement?(p=t,f=t.documentElement,h=!s(t),r&&r.attachEvent&&r!==r.top&&r.attachEvent("onbeforeunload",function(){c()}),n.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ut(function(e){return e.appendChild(t.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=ut(function(e){return e.innerHTML="
",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),n.getById=ut(function(e){return f.appendChild(e).id=v,!t.getElementsByName||!t.getElementsByName(v).length}),n.getById?(i.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(nt,rt);return function(e){return e.getAttribute("id")===t}}):(delete i.find.ID,i.filter.ID=function(e){var t=e.replace(nt,rt);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=n.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==j?t.getElementsByTagName(e):undefined}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.CLASS=n.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==j&&h?t.getElementsByClassName(e):undefined},g=[],d=[],(n.qsa=Q.test(t.querySelectorAll))&&(ut(function(e){e.innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll(":checked").length||d.push(":checked")}),ut(function(e){var n=t.createElement("input");n.setAttribute("type","hidden"),e.appendChild(n).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&d.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||d.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),d.push(",.*:")})),(n.matchesSelector=Q.test(m=f.webkitMatchesSelector||f.mozMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&ut(function(e){n.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",I)}),d=d.length&&RegExp(d.join("|")),g=g.length&&RegExp(g.join("|")),y=Q.test(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},S=f.compareDocumentPosition?function(e,r){if(e===r)return E=!0,0;var i=r.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(r);return i?1&i||!n.sortDetached&&r.compareDocumentPosition(e)===i?e===t||y(b,e)?-1:r===t||y(b,r)?1:l?P.call(l,e)-P.call(l,r):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,n){var r,i=0,o=e.parentNode,s=n.parentNode,a=[e],u=[n];if(e===n)return E=!0,0;if(!o||!s)return e===t?-1:n===t?1:o?-1:s?1:l?P.call(l,e)-P.call(l,n):0;if(o===s)return ct(e,n);r=e;while(r=r.parentNode)a.unshift(r);r=n;while(r=r.parentNode)u.unshift(r);while(a[i]===u[i])i++;return i?ct(a[i],u[i]):a[i]===b?-1:u[i]===b?1:0},t):p},ot.matches=function(e,t){return ot(e,null,null,t)},ot.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Y,"='$1']"),!(!n.matchesSelector||!h||g&&g.test(t)||d&&d.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return ot(t,p,null,[e]).length>0},ot.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},ot.attr=function(e,t){(e.ownerDocument||e)!==p&&c(e);var r=i.attrHandle[t.toLowerCase()],o=r&&A.call(i.attrHandle,t.toLowerCase())?r(e,t,!h):undefined;return o===undefined?n.attributes||!h?e.getAttribute(t):(o=e.getAttributeNode(t))&&o.specified?o.value:null:o},ot.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},ot.uniqueSort=function(e){var t,r=[],i=0,o=0;if(E=!n.detectDuplicates,l=!n.sortStable&&e.slice(0),e.sort(S),E){while(t=e[o++])t===e[o]&&(i=r.push(o));while(i--)e.splice(r[i],1)}return e},o=ot.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=ot.selectors={cacheLength:50,createPseudo:at,match:J,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(nt,rt),e[3]=(e[4]||e[5]||"").replace(nt,rt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||ot.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&ot.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return J.CHILD.test(e[0])?null:(e[3]&&e[4]!==undefined?e[2]=e[4]:n&&V.test(n)&&(t=gt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(nt,rt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=C[e+" "];return t||(t=RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&C(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=ot.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,h,d,g=o!==s?"nextSibling":"previousSibling",m=t.parentNode,y=a&&t.nodeName.toLowerCase(),x=!u&&!a;if(m){if(o){while(g){p=t;while(p=p[g])if(a?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;d=g="only"===e&&!d&&"nextSibling"}return!0}if(d=[s?m.firstChild:m.lastChild],s&&x){c=m[v]||(m[v]={}),l=c[e]||[],h=l[0]===w&&l[1],f=l[0]===w&&l[2],p=h&&m.childNodes[h];while(p=++h&&p&&p[g]||(f=h=0)||d.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[w,h,f];break}}else if(x&&(l=(t[v]||(t[v]={}))[e])&&l[0]===w)f=l[1];else while(p=++h&&p&&p[g]||(f=h=0)||d.pop())if((a?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(x&&((p[v]||(p[v]={}))[e]=[w,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||ot.error("unsupported pseudo: "+e);return r[v]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?at(function(e,n){var i,o=r(e,t),s=o.length;while(s--)i=P.call(e,o[s]),e[i]=!(n[i]=o[s])}):function(e){return r(e,0,n)}):r}},pseudos:{not:at(function(e){var t=[],n=[],r=a(e.replace(z,"$1"));return r[v]?at(function(e,t,n,i){var o,s=r(e,null,i,[]),a=e.length;while(a--)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:at(function(e){return function(t){return ot(e,t).length>0}}),contains:at(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:at(function(e){return G.test(e||"")||ot.error("unsupported lang: "+e),e=e.replace(nt,rt).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return et.test(e.nodeName)},input:function(e){return Z.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},i.pseudos.nth=i.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[t]=pt(t);for(t in{submit:!0,reset:!0})i.pseudos[t]=ft(t);function dt(){}dt.prototype=i.filters=i.pseudos,i.setFilters=new dt;function gt(e,t){var n,r,o,s,a,u,l,c=k[e+" "];if(c)return t?0:c.slice(0);a=e,u=[],l=i.preFilter;while(a){(!n||(r=_.exec(a)))&&(r&&(a=a.slice(r[0].length)||a),u.push(o=[])),n=!1,(r=X.exec(a))&&(n=r.shift(),o.push({value:n,type:r[0].replace(z," ")}),a=a.slice(n.length));for(s in i.filter)!(r=J[s].exec(a))||l[s]&&!(r=l[s](r))||(n=r.shift(),o.push({value:n,type:s,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?ot.error(e):k(e,u).slice(0)}function mt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function yt(e,t,n){var i=t.dir,o=n&&"parentNode"===i,s=T++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,a){var u,l,c,p=w+" "+s;if(a){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,a))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[v]||(t[v]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,a)||r,l[1]===!0)return!0}}function vt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,s=[],a=0,u=e.length,l=null!=t;for(;u>a;a++)(o=e[a])&&(!n||n(o,r,i))&&(s.push(o),l&&t.push(a));return s}function bt(e,t,n,r,i,o){return r&&!r[v]&&(r=bt(r)),i&&!i[v]&&(i=bt(i,o)),at(function(o,s,a,u){var l,c,p,f=[],h=[],d=s.length,g=o||Ct(t||"*",a.nodeType?[a]:a,[]),m=!e||!o&&t?g:xt(g,f,e,a,u),y=n?i||(o?e:d||r)?[]:s:m;if(n&&n(m,y,a,u),r){l=xt(y,h),r(l,[],a,u),c=l.length;while(c--)(p=l[c])&&(y[h[c]]=!(m[h[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?P.call(o,p):f[c])>-1&&(o[l]=!(s[l]=p))}}else y=xt(y===s?y.splice(d,y.length):y),i?i(null,s,y,u):O.apply(s,y)})}function wt(e){var t,n,r,o=e.length,s=i.relative[e[0].type],a=s||i.relative[" "],l=s?1:0,c=yt(function(e){return e===t},a,!0),p=yt(function(e){return P.call(t,e)>-1},a,!0),f=[function(e,n,r){return!s&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>l;l++)if(n=i.relative[e[l].type])f=[yt(vt(f),n)];else{if(n=i.filter[e[l].type].apply(null,e[l].matches),n[v]){for(r=++l;o>r;r++)if(i.relative[e[r].type])break;return bt(l>1&&vt(f),l>1&&mt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&wt(e.slice(l,r)),o>r&&wt(e=e.slice(r)),o>r&&mt(e))}f.push(n)}return vt(f)}function Tt(e,t){var n=0,o=t.length>0,s=e.length>0,a=function(a,l,c,f,h){var d,g,m,y=[],v=0,x="0",b=a&&[],T=null!=h,C=u,k=a||s&&i.find.TAG("*",h&&l.parentNode||l),N=w+=null==C?1:Math.random()||.1;for(T&&(u=l!==p&&l,r=n);null!=(d=k[x]);x++){if(s&&d){g=0;while(m=e[g++])if(m(d,l,c)){f.push(d);break}T&&(w=N,r=++n)}o&&((d=!m&&d)&&v--,a&&b.push(d))}if(v+=x,o&&x!==v){g=0;while(m=t[g++])m(b,y,l,c);if(a){if(v>0)while(x--)b[x]||y[x]||(y[x]=q.call(f));y=xt(y)}O.apply(f,y),T&&!a&&y.length>0&&v+t.length>1&&ot.uniqueSort(f)}return T&&(w=N,u=C),b};return o?at(a):a}a=ot.compile=function(e,t){var n,r=[],i=[],o=N[e+" "];if(!o){t||(t=gt(e)),n=t.length;while(n--)o=wt(t[n]),o[v]?r.push(o):i.push(o);o=N(e,Tt(i,r))}return o};function Ct(e,t,n){var r=0,i=t.length;for(;i>r;r++)ot(e,t[r],n);return n}function kt(e,t,r,o){var s,u,l,c,p,f=gt(e);if(!o&&1===f.length){if(u=f[0]=f[0].slice(0),u.length>2&&"ID"===(l=u[0]).type&&n.getById&&9===t.nodeType&&h&&i.relative[u[1].type]){if(t=(i.find.ID(l.matches[0].replace(nt,rt),t)||[])[0],!t)return r;e=e.slice(u.shift().value.length)}s=J.needsContext.test(e)?0:u.length;while(s--){if(l=u[s],i.relative[c=l.type])break;if((p=i.find[c])&&(o=p(l.matches[0].replace(nt,rt),U.test(u[0].type)&&t.parentNode||t))){if(u.splice(s,1),e=o.length&&mt(u),!e)return O.apply(r,o),r;break}}}return a(e,f)(o,t,!h,r,U.test(e)),r}n.sortStable=v.split("").sort(S).join("")===v,n.detectDuplicates=E,c(),n.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(p.createElement("div"))}),ut(function(e){return e.innerHTML="","#"===e.firstChild.getAttribute("href")})||lt("type|href|height|width",function(e,t,n){return n?undefined:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),n.attributes&&ut(function(e){return e.innerHTML="",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||lt("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?undefined:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||lt(R,function(e,t,n){var r;return n?undefined:(r=e.getAttributeNode(t))&&r.specified?r.value:e[t]===!0?t.toLowerCase():null}),x.find=ot,x.expr=ot.selectors,x.expr[":"]=x.expr.pseudos,x.unique=ot.uniqueSort,x.text=ot.getText,x.isXMLDoc=ot.isXML,x.contains=ot.contains}(e);var D={};function A(e){var t=D[e]={};return x.each(e.match(w)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?D[e]||A(e):x.extend({},e);var t,n,r,i,o,s,a=[],u=!e.once&&[],l=function(p){for(t=e.memory&&p,n=!0,s=i||0,i=0,o=a.length,r=!0;a&&o>s;s++)if(a[s].apply(p[0],p[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,a&&(u?u.length&&l(u.shift()):t?a=[]:c.disable())},c={add:function(){if(a){var n=a.length;(function s(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&c.has(n)||a.push(n):n&&n.length&&"string"!==r&&s(n)})})(arguments),r?o=a.length:t&&(i=n,l(t))}return this},remove:function(){return a&&x.each(arguments,function(e,t){var n;while((n=x.inArray(t,a,n))>-1)a.splice(n,1),r&&(o>=n&&o--,s>=n&&s--)}),this},has:function(e){return e?x.inArray(e,a)>-1:!(!a||!a.length)},empty:function(){return a=[],o=0,this},disable:function(){return a=u=t=undefined,this},disabled:function(){return!a},lock:function(){return u=undefined,t||c.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!a||n&&!u||(t=t||[],t=[e,t.slice?t.slice():t],r?u.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!n}};return c},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var s=o[0],a=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add,a&&s.add(function(){n=a},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=s.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=d.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),s=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?d.call(arguments):r,n===a?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},a,u,l;if(r>1)for(a=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(s(t,l,n)).fail(o.reject).progress(s(t,u,a)):--i;return i||o.resolveWith(l,n),o.promise()}}),x.support=function(t){var n=o.createElement("input"),r=o.createDocumentFragment(),i=o.createElement("div"),s=o.createElement("select"),a=s.appendChild(o.createElement("option"));return n.type?(n.type="checkbox",t.checkOn=""!==n.value,t.optSelected=a.selected,t.reliableMarginRight=!0,t.boxSizingReliable=!0,t.pixelPosition=!1,n.checked=!0,t.noCloneChecked=n.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!a.disabled,n=o.createElement("input"),n.value="t",n.type="radio",t.radioValue="t"===n.value,n.setAttribute("checked","t"),n.setAttribute("name","t"),r.appendChild(n),t.checkClone=r.cloneNode(!0).cloneNode(!0).lastChild.checked,t.focusinBubbles="onfocusin"in e,i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===i.style.backgroundClip,x(function(){var n,r,s="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",a=o.getElementsByTagName("body")[0];a&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",a.appendChild(n).appendChild(i),i.innerHTML="",i.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",x.swap(a,null!=a.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===i.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(i,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(i,null)||{width:"4px"}).width,r=i.appendChild(o.createElement("div")),r.style.cssText=i.style.cssText=s,r.style.marginRight=r.style.width="0",i.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),a.removeChild(n))}),t):t}({});var L,q,H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,O=/([A-Z])/g;function F(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=x.expando+Math.random()}F.uid=1,F.accepts=function(e){return e.nodeType?1===e.nodeType||9===e.nodeType:!0},F.prototype={key:function(e){if(!F.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=F.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,x.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),o=this.cache[i];if("string"==typeof t)o[t]=n;else if(x.isEmptyObject(o))x.extend(this.cache[i],t);else for(r in t)o[r]=t[r];return o},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){var r;return t===undefined||t&&"string"==typeof t&&n===undefined?(r=this.get(e,t),r!==undefined?r:this.get(e,x.camelCase(t))):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i,o=this.key(e),s=this.cache[o];if(t===undefined)this.cache[o]={};else{x.isArray(t)?r=t.concat(t.map(x.camelCase)):(i=x.camelCase(t),t in s?r=[t,i]:(r=i,r=r in s?[r]:r.match(w)||[])),n=r.length;while(n--)delete s[r[n]]}},hasData:function(e){return!x.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){e[this.expando]&&delete this.cache[e[this.expando]]}},L=new F,q=new F,x.extend({acceptData:F.accepts,hasData:function(e){return L.hasData(e)||q.hasData(e)},data:function(e,t,n){return L.access(e,t,n)},removeData:function(e,t){L.remove(e,t)},_data:function(e,t,n){return q.access(e,t,n)},_removeData:function(e,t){q.remove(e,t)}}),x.fn.extend({data:function(e,t){var n,r,i=this[0],o=0,s=null;if(e===undefined){if(this.length&&(s=L.get(i),1===i.nodeType&&!q.get(i,"hasDataAttrs"))){for(n=i.attributes;n.length>o;o++)r=n[o].name,0===r.indexOf("data-")&&(r=x.camelCase(r.slice(5)),P(i,r,s[r]));q.set(i,"hasDataAttrs",!0)}return s}return"object"==typeof e?this.each(function(){L.set(this,e)}):x.access(this,function(t){var n,r=x.camelCase(e);if(i&&t===undefined){if(n=L.get(i,e),n!==undefined)return n;if(n=L.get(i,r),n!==undefined)return n;if(n=P(i,r,undefined),n!==undefined)return n}else this.each(function(){var n=L.get(this,r);L.set(this,r,t),-1!==e.indexOf("-")&&n!==undefined&&L.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){L.remove(this,e)})}});function P(e,t,n){var r;if(n===undefined&&1===e.nodeType)if(r="data-"+t.replace(O,"-$1").toLowerCase(),n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:H.test(n)?JSON.parse(n):n}catch(i){}L.set(e,t,n)}else n=undefined;return n}x.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=q.get(e,t),n&&(!r||x.isArray(n)?r=q.access(e,t,x.makeArray(n)):r.push(n)),r||[]):undefined},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),s=function(){x.dequeue(e,t) -};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,s,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return q.get(e,n)||q.access(e,n,{empty:x.Callbacks("once memory").add(function(){q.remove(e,[t+"queue",n])})})}}),x.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),n>arguments.length?x.queue(this[0],e):t===undefined?this:this.each(function(){var n=x.queue(this,e,t);x._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=x.Deferred(),o=this,s=this.length,a=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=undefined),e=e||"fx";while(s--)n=q.get(o[s],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(a));return a(),i.promise(t)}});var R,M,W=/[\t\r\n\f]/g,$=/\r/g,B=/^(?:input|select|textarea|button)$/i;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[x.propFix[e]||e]})},addClass:function(e){var t,n,r,i,o,s=0,a=this.length,u="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,s=0,a=this.length,u=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];a>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(W," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,i=0,o=x(this),s=e.match(w)||[];while(t=s[i++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===r||"boolean"===n)&&(this.className&&q.set(this,"__className__",this.className),this.className=this.className||e===!1?"":q.get(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(W," ").indexOf(t)>=0)return!0;return!1},val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=x.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,x(this).val()):e,null==i?i="":"number"==typeof i?i+="":x.isArray(i)&&(i=x.map(i,function(e){return null==e?"":e+""})),t=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&t.set(this,i,"value")!==undefined||(this.value=i))});if(i)return t=x.valHooks[i.type]||x.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,"string"==typeof n?n.replace($,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,s=o?null:[],a=o?i+1:r.length,u=0>i?a:o?i:0;for(;a>u;u++)if(n=r[u],!(!n.selected&&u!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),s=i.length;while(s--)r=i[s],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,t,n){var i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===r?x.prop(e,t,n):(1===s&&x.isXMLDoc(e)||(t=t.toLowerCase(),i=x.attrHooks[t]||(x.expr.match.bool.test(t)?M:R)),n===undefined?i&&"get"in i&&null!==(o=i.get(e,t))?o:(o=x.find.attr(e,t),null==o?undefined:o):null!==n?i&&"set"in i&&(o=i.set(e,n,t))!==undefined?o:(e.setAttribute(t,n+""),n):(x.removeAttr(e,t),undefined))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return o=1!==s||!x.isXMLDoc(e),o&&(t=x.propFix[t]||t,i=x.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||B.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),M={set:function(e,t,n){return t===!1?x.removeAttr(e,n):e.setAttribute(n,n),n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,t){var n=x.expr.attrHandle[t]||x.find.attr;x.expr.attrHandle[t]=function(e,t,r){var i=x.expr.attrHandle[t],o=r?undefined:(x.expr.attrHandle[t]=undefined)!=n(e,t,r)?t.toLowerCase():null;return x.expr.attrHandle[t]=i,o}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,t){return x.isArray(t)?e.checked=x.inArray(x(e).val(),t)>=0:undefined}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var I=/^key/,z=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,X=/^([^.]*)(?:\.(.+)|)$/;function U(){return!0}function Y(){return!1}function V(){try{return o.activeElement}catch(e){}}x.event={global:{},add:function(e,t,n,i,o){var s,a,u,l,c,p,f,h,d,g,m,y=q.get(e);if(y){n.handler&&(s=n,n=s.handler,o=s.selector),n.guid||(n.guid=x.guid++),(l=y.events)||(l=y.events={}),(a=y.handle)||(a=y.handle=function(e){return typeof x===r||e&&x.event.triggered===e.type?undefined:x.event.dispatch.apply(a.elem,arguments)},a.elem=e),t=(t||"").match(w)||[""],c=t.length;while(c--)u=X.exec(t[c])||[],d=m=u[1],g=(u[2]||"").split(".").sort(),d&&(f=x.event.special[d]||{},d=(o?f.delegateType:f.bindType)||d,f=x.event.special[d]||{},p=x.extend({type:d,origType:m,data:i,handler:n,guid:n.guid,selector:o,needsContext:o&&x.expr.match.needsContext.test(o),namespace:g.join(".")},s),(h=l[d])||(h=l[d]=[],h.delegateCount=0,f.setup&&f.setup.call(e,i,g,a)!==!1||e.addEventListener&&e.addEventListener(d,a,!1)),f.add&&(f.add.call(e,p),p.handler.guid||(p.handler.guid=n.guid)),o?h.splice(h.delegateCount++,0,p):h.push(p),x.event.global[d]=!0);e=null}},remove:function(e,t,n,r,i){var o,s,a,u,l,c,p,f,h,d,g,m=q.hasData(e)&&q.get(e);if(m&&(u=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(a=X.exec(t[l])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){p=x.event.special[h]||{},h=(r?p.delegateType:p.bindType)||h,f=u[h]||[],a=a[2]&&RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=o=f.length;while(o--)c=f[o],!i&&g!==c.origType||n&&n.guid!==c.guid||a&&!a.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(f.splice(o,1),c.selector&&f.delegateCount--,p.remove&&p.remove.call(e,c));s&&!f.length&&(p.teardown&&p.teardown.call(e,d,m.handle)!==!1||x.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)x.event.remove(e,h+t[l],n,r,!0);x.isEmptyObject(u)&&(delete m.handle,q.remove(e,"events"))}},trigger:function(t,n,r,i){var s,a,u,l,c,p,f,h=[r||o],d=y.call(t,"type")?t.type:t,g=y.call(t,"namespace")?t.namespace.split("."):[];if(a=u=r=r||o,3!==r.nodeType&&8!==r.nodeType&&!_.test(d+x.event.triggered)&&(d.indexOf(".")>=0&&(g=d.split("."),d=g.shift(),g.sort()),c=0>d.indexOf(":")&&"on"+d,t=t[x.expando]?t:new x.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=g.join("."),t.namespace_re=t.namespace?RegExp("(^|\\.)"+g.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=undefined,t.target||(t.target=r),n=null==n?[t]:x.makeArray(n,[t]),f=x.event.special[d]||{},i||!f.trigger||f.trigger.apply(r,n)!==!1)){if(!i&&!f.noBubble&&!x.isWindow(r)){for(l=f.delegateType||d,_.test(l+d)||(a=a.parentNode);a;a=a.parentNode)h.push(a),u=a;u===(r.ownerDocument||o)&&h.push(u.defaultView||u.parentWindow||e)}s=0;while((a=h[s++])&&!t.isPropagationStopped())t.type=s>1?l:f.bindType||d,p=(q.get(a,"events")||{})[t.type]&&q.get(a,"handle"),p&&p.apply(a,n),p=c&&a[c],p&&x.acceptData(a)&&p.apply&&p.apply(a,n)===!1&&t.preventDefault();return t.type=d,i||t.isDefaultPrevented()||f._default&&f._default.apply(h.pop(),n)!==!1||!x.acceptData(r)||c&&x.isFunction(r[d])&&!x.isWindow(r)&&(u=r[c],u&&(r[c]=null),x.event.triggered=d,r[d](),x.event.triggered=undefined,u&&(r[c]=u)),t.result}},dispatch:function(e){e=x.event.fix(e);var t,n,r,i,o,s=[],a=d.call(arguments),u=(q.get(this,"events")||{})[e.type]||[],l=x.event.special[e.type]||{};if(a[0]=e,e.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),t=0;while((i=s[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(o.namespace))&&(e.handleObj=o,e.data=o.data,r=((x.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,a),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return l.postDispatch&&l.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,s=[],a=t.delegateCount,u=e.target;if(a&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!==this;u=u.parentNode||this)if(u.disabled!==!0||"click"!==e.type){for(r=[],n=0;a>n;n++)o=t[n],i=o.selector+" ",r[i]===undefined&&(r[i]=o.needsContext?x(i,this).index(u)>=0:x.find(i,this,null,[u]).length),r[i]&&r.push(o);r.length&&s.push({elem:u,handlers:r})}return t.length>a&&s.push({elem:this,handlers:t.slice(a)}),s},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return null==e.pageX&&null!=t.clientX&&(n=e.target.ownerDocument||o,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),e.which||s===undefined||(e.which=1&s?1:2&s?3:4&s?2:0),e}},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,s=e,a=this.fixHooks[i];a||(this.fixHooks[i]=a=z.test(i)?this.mouseHooks:I.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new x.Event(s),t=r.length;while(t--)n=r[t],e[n]=s[n];return e.target||(e.target=o),3===e.target.nodeType&&(e.target=e.target.parentNode),a.filter?a.filter(e,s):e},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==V()&&this.focus?(this.focus(),!1):undefined},delegateType:"focusin"},blur:{trigger:function(){return this===V()&&this.blur?(this.blur(),!1):undefined},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&x.nodeName(this,"input")?(this.click(),!1):undefined},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},x.Event=function(e,t){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.getPreventDefault&&e.getPreventDefault()?U:Y):this.type=e,t&&x.extend(this,t),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,undefined):new x.Event(e,t)},x.Event.prototype={isDefaultPrevented:Y,isPropagationStopped:Y,isImmediatePropagationStopped:Y,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=U,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=U,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=U,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,t,n,r,i){var o,s;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=undefined);for(s in e)this.on(s,t,n,e[s],i);return this}if(null==n&&null==r?(r=t,n=t=undefined):null==r&&("string"==typeof t?(r=n,n=undefined):(r=n,n=t,t=undefined)),r===!1)r=Y;else if(!r)return this;return 1===i&&(o=r,r=function(e){return x().off(e),o.apply(this,arguments)},r.guid=o.guid||(o.guid=x.guid++)),this.each(function(){x.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,x(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=undefined),n===!1&&(n=Y),this.each(function(){x.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?x.event.trigger(e,t,n,!0):undefined}});var G=/^.[^:#\[\.,]*$/,J=/^(?:parents|prev(?:Until|All))/,Q=x.expr.match.needsContext,K={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t=x(e,this),n=t.length;return this.filter(function(){var e=0;for(;n>e;e++)if(x.contains(this,t[e]))return!0})},not:function(e){return this.pushStack(et(this,e||[],!0))},filter:function(e){return this.pushStack(et(this,e||[],!1))},is:function(e){return!!et(this,"string"==typeof e&&Q.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],s=Q.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(s?s.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?g.call(x(e),this[0]):g.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function Z(e,t){while((e=e[t])&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return Z(e,"nextSibling")},prev:function(e){return Z(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return e.contentDocument||x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(K[e]||x.unique(i),J.test(e)&&i.reverse()),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&x(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function et(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(G.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return g.call(t,e)>=0!==n})}var tt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,nt=/<([\w:]+)/,rt=/<|&#?\w+;/,it=/<(?:script|style|link)/i,ot=/^(?:checkbox|radio)$/i,st=/checked\s*(?:[^=]|=\s*.checked.)/i,at=/^$|\/(?:java|ecma)script/i,ut=/^true\/(.*)/,lt=/^\s*\s*$/g,ct={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ct.optgroup=ct.option,ct.tbody=ct.tfoot=ct.colgroup=ct.caption=ct.thead,ct.th=ct.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===undefined?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=pt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=pt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(mt(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&dt(mt(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++)1===e.nodeType&&(x.cleanData(mt(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!it.test(e)&&!ct[(nt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(tt,"<$1>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(x.cleanData(mt(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=f.apply([],e);var r,i,o,s,a,u,l=0,c=this.length,p=this,h=c-1,d=e[0],g=x.isFunction(d);if(g||!(1>=c||"string"!=typeof d||x.support.checkClone)&&st.test(d))return this.each(function(r){var i=p.eq(r);g&&(e[0]=d.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(r=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),i=r.firstChild,1===r.childNodes.length&&(r=i),i)){for(o=x.map(mt(r,"script"),ft),s=o.length;c>l;l++)a=r,l!==h&&(a=x.clone(a,!0,!0),s&&x.merge(o,mt(a,"script"))),t.call(this[l],a,l);if(s)for(u=o[o.length-1].ownerDocument,x.map(o,ht),l=0;s>l;l++)a=o[l],at.test(a.type||"")&&!q.access(a,"globalEval")&&x.contains(u,a)&&(a.src?x._evalUrl(a.src):x.globalEval(a.textContent.replace(lt,"")))}return this}}),x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=[],i=x(e),o=i.length-1,s=0;for(;o>=s;s++)n=s===o?this:this.clone(!0),x(i[s])[t](n),h.apply(r,n.get());return this.pushStack(r)}}),x.extend({clone:function(e,t,n){var r,i,o,s,a=e.cloneNode(!0),u=x.contains(e.ownerDocument,e);if(!(x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(s=mt(a),o=mt(e),r=0,i=o.length;i>r;r++)yt(o[r],s[r]);if(t)if(n)for(o=o||mt(e),s=s||mt(a),r=0,i=o.length;i>r;r++)gt(o[r],s[r]);else gt(e,a);return s=mt(a,"script"),s.length>0&&dt(s,!u&&mt(e,"script")),a},buildFragment:function(e,t,n,r){var i,o,s,a,u,l,c=0,p=e.length,f=t.createDocumentFragment(),h=[];for(;p>c;c++)if(i=e[c],i||0===i)if("object"===x.type(i))x.merge(h,i.nodeType?[i]:i);else if(rt.test(i)){o=o||f.appendChild(t.createElement("div")),s=(nt.exec(i)||["",""])[1].toLowerCase(),a=ct[s]||ct._default,o.innerHTML=a[1]+i.replace(tt,"<$1>")+a[2],l=a[0];while(l--)o=o.lastChild;x.merge(h,o.childNodes),o=f.firstChild,o.textContent=""}else h.push(t.createTextNode(i));f.textContent="",c=0;while(i=h[c++])if((!r||-1===x.inArray(i,r))&&(u=x.contains(i.ownerDocument,i),o=mt(f.appendChild(i),"script"),u&&dt(o),n)){l=0;while(i=o[l++])at.test(i.type||"")&&n.push(i)}return f},cleanData:function(e){var t,n,r,i,o,s,a=x.event.special,u=0;for(;(n=e[u])!==undefined;u++){if(F.accepts(n)&&(o=n[q.expando],o&&(t=q.cache[o]))){if(r=Object.keys(t.events||{}),r.length)for(s=0;(i=r[s])!==undefined;s++)a[i]?x.event.remove(n,i):x.removeEvent(n,i,t.handle);q.cache[o]&&delete q.cache[o]}delete L.cache[n[L.expando]]}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}});function pt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function ft(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function ht(e){var t=ut.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function dt(e,t){var n=e.length,r=0;for(;n>r;r++)q.set(e[r],"globalEval",!t||q.get(t[r],"globalEval"))}function gt(e,t){var n,r,i,o,s,a,u,l;if(1===t.nodeType){if(q.hasData(e)&&(o=q.access(e),s=q.set(t,o),l=o.events)){delete s.handle,s.events={};for(i in l)for(n=0,r=l[i].length;r>n;n++)x.event.add(t,i,l[i][n])}L.hasData(e)&&(a=L.access(e),u=x.extend({},a),L.set(t,u))}}function mt(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&x.nodeName(e,t)?x.merge([e],n):n}function yt(e,t){var n=t.nodeName.toLowerCase();"input"===n&&ot.test(e.type)?t.checked=e.checked:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}x.fn.extend({wrapAll:function(e){var t;return x.isFunction(e)?this.each(function(t){x(this).wrapAll(e.call(this,t))}):(this[0]&&(t=x(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var vt,xt,bt=/^(none|table(?!-c[ea]).+)/,wt=/^margin/,Tt=RegExp("^("+b+")(.*)$","i"),Ct=RegExp("^("+b+")(?!px)[a-z%]+$","i"),kt=RegExp("^([+-])=("+b+")","i"),Nt={BODY:"block"},Et={position:"absolute",visibility:"hidden",display:"block"},St={letterSpacing:0,fontWeight:400},jt=["Top","Right","Bottom","Left"],Dt=["Webkit","O","Moz","ms"];function At(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Dt.length;while(i--)if(t=Dt[i]+n,t in e)return t;return r}function Lt(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function qt(t){return e.getComputedStyle(t,null)}function Ht(e,t){var n,r,i,o=[],s=0,a=e.length;for(;a>s;s++)r=e[s],r.style&&(o[s]=q.get(r,"olddisplay"),n=r.style.display,t?(o[s]||"none"!==n||(r.style.display=""),""===r.style.display&&Lt(r)&&(o[s]=q.access(r,"olddisplay",Rt(r.nodeName)))):o[s]||(i=Lt(r),(n&&"none"!==n||!i)&&q.set(r,"olddisplay",i?n:x.css(r,"display"))));for(s=0;a>s;s++)r=e[s],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"));return e}x.fn.extend({css:function(e,t){return x.access(this,function(e,t,n){var r,i,o={},s=0;if(x.isArray(t)){for(r=qt(e),i=t.length;i>s;s++)o[t[s]]=x.css(e,t[s],!1,r);return o}return n!==undefined?x.style(e,t,n):x.css(e,t)},e,t,arguments.length>1)},show:function(){return Ht(this,!0)},hide:function(){return Ht(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){Lt(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=vt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,s,a=x.camelCase(t),u=e.style;return t=x.cssProps[a]||(x.cssProps[a]=At(u,a)),s=x.cssHooks[t]||x.cssHooks[a],n===undefined?s&&"get"in s&&(i=s.get(e,!1,r))!==undefined?i:u[t]:(o=typeof n,"string"===o&&(i=kt.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(x.css(e,t)),o="number"),null==n||"number"===o&&isNaN(n)||("number"!==o||x.cssNumber[a]||(n+="px"),x.support.clearCloneStyle||""!==n||0!==t.indexOf("background")||(u[t]="inherit"),s&&"set"in s&&(n=s.set(e,n,r))===undefined||(u[t]=n)),undefined)}},css:function(e,t,n,r){var i,o,s,a=x.camelCase(t);return t=x.cssProps[a]||(x.cssProps[a]=At(e.style,a)),s=x.cssHooks[t]||x.cssHooks[a],s&&"get"in s&&(i=s.get(e,!0,n)),i===undefined&&(i=vt(e,t,r)),"normal"===i&&t in St&&(i=St[t]),""===n||n?(o=parseFloat(i),n===!0||x.isNumeric(o)?o||0:i):i}}),vt=function(e,t,n){var r,i,o,s=n||qt(e),a=s?s.getPropertyValue(t)||s[t]:undefined,u=e.style;return s&&(""!==a||x.contains(e.ownerDocument,e)||(a=x.style(e,t)),Ct.test(a)&&wt.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=s.width,u.width=r,u.minWidth=i,u.maxWidth=o)),a};function Ot(e,t,n){var r=Tt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function Ft(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,s=0;for(;4>o;o+=2)"margin"===n&&(s+=x.css(e,n+jt[o],!0,i)),r?("content"===n&&(s-=x.css(e,"padding"+jt[o],!0,i)),"margin"!==n&&(s-=x.css(e,"border"+jt[o]+"Width",!0,i))):(s+=x.css(e,"padding"+jt[o],!0,i),"padding"!==n&&(s+=x.css(e,"border"+jt[o]+"Width",!0,i)));return s}function Pt(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=qt(e),s=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=vt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Ct.test(i))return i;r=s&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+Ft(e,t,n||(s?"border":"content"),r,o)+"px"}function Rt(e){var t=o,n=Nt[e];return n||(n=Mt(e,t),"none"!==n&&n||(xt=(xt||x(" - - - \ No newline at end of file diff --git a/examples/sprites/add a sprite.js b/examples/sprites/add a sprite.js deleted file mode 100644 index 142af5400..000000000 --- a/examples/sprites/add a sprite.js +++ /dev/null @@ -1,15 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -function create() { - - // This simply creates a sprite using the mushroom image we loaded above and positions it at 200 x 200 - var test = game.add.sprite(200, 200, 'mushroom'); - -} diff --git a/examples/sprites/add several sprites.js b/examples/sprites/add several sprites.js deleted file mode 100644 index 685e83f98..000000000 --- a/examples/sprites/add several sprites.js +++ /dev/null @@ -1,49 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -var timer = 0; -var total = 0; - -function preload() { - - // 37x45 is the size of each frame - // There are 18 frames in the PNG - you can leave this value blank if the frames fill up the entire PNG, but in this case there are some - // blank frames at the end, so we tell the loader how many to load - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -function create() { - - releaseMummy(); - -} - -function releaseMummy() { - - var mummy = game.add.sprite(-(Math.random() * 800), game.world.randomY, 'mummy'); - - mummy.scale.setTo(2, 2); - - // If you prefer to work in degrees rather than radians then you can use Phaser.Sprite.angle - // otherwise use Phaser.Sprite.rotation - mummy.angle = game.rnd.angle(); - - mummy.animations.add('walk'); - mummy.animations.play('walk', 20, true); - - game.add.tween(mummy).to({ x: game.width + (1600 + mummy.x) }, 20000, Phaser.Easing.Linear.None, true); - - total++; - timer = game.time.now + 100; - -} - -function update() { - - if (total < 200 && game.time.now > timer) - { - releaseMummy(); - } - -} diff --git a/examples/sprites/collide world bounds.js b/examples/sprites/collide world bounds.js deleted file mode 100644 index 622e1a834..000000000 --- a/examples/sprites/collide world bounds.js +++ /dev/null @@ -1,28 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - game.load.image('pineapple', 'assets/sprites/pineapple.png'); - -} - -var pineapples; - -function create() { - - pineapples = game.add.group(); - pineapples.enableBody = true; - pineapples.physicsBodyType = Phaser.Physics.ARCADE; - - for (var i = 0; i < 10; i++) - { - var pineapple = pineapples.create(200 + i * 48,50, 'pineapple'); - - //This allows your sprite to collide with the world bounds like they were rigid objects - pineapple.body.collideWorldBounds=true; - pineapple.body.gravity.x = game.rnd.integerInRange(-5,5); - pineapple.body.gravity.y = 5 + Math.random() * 10; - pineapple.body.bounce.setTo(0.7,0.4); - } - -} diff --git a/examples/sprites/destroy.js b/examples/sprites/destroy.js deleted file mode 100644 index 38d65a18b..000000000 --- a/examples/sprites/destroy.js +++ /dev/null @@ -1,31 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('plane', 'assets/misc/boss1.png'); - game.load.image('sky', 'assets/tests/sky-2x.png'); - -} - -function create() { - - game.add.sprite(0, 0, 'sky'); - - for (var i = 0; i < 15; i++) - { - var sprite = game.add.sprite(game.world.randomX, game.world.randomY, 'plane'); - - sprite.inputEnabled = true; - - sprite.input.useHandCursor = true; - - sprite.events.onInputDown.add(destoyIt, this); - } - -} - -function destoyIt (sprite) { - - sprite.destroy(); -} diff --git a/examples/sprites/dynamic crop.js b/examples/sprites/dynamic crop.js deleted file mode 100644 index 3309704dd..000000000 --- a/examples/sprites/dynamic crop.js +++ /dev/null @@ -1,42 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - game.load.image('trsi', 'assets/pics/trsipic1_lazur.jpg'); -} - -var pic; -var cropRect; - -function create() { - - pic = game.add.sprite(0, 0, 'trsi'); - - cropRect = {x : 0, y : 0 , width : 128, height : 128}; -} - -function update() { - - if(game.input.x < pic.width && game.input.y < pic.height){ - - pic.x = game.input.x; - pic.y = game.input.y; - - cropRect.x = game.input.x; - cropRect.y = game.input.y; - - pic.crop(cropRect); - - - - } - - - -} - -function render() { - - game.debug.text('x: ' + game.input.x + ' y: ' + game.input.y, 32, 32); - -} diff --git a/examples/sprites/extending sprite demo 1.js b/examples/sprites/extending sprite demo 1.js deleted file mode 100644 index 2d0da102c..000000000 --- a/examples/sprites/extending sprite demo 1.js +++ /dev/null @@ -1,42 +0,0 @@ - -// Here is a custom game object -MonsterBunny = function (game, x, y, rotateSpeed) { - - Phaser.Sprite.call(this, game, x, y, 'bunny'); - - this.rotateSpeed = rotateSpeed; - -}; - -MonsterBunny.prototype = Object.create(Phaser.Sprite.prototype); -MonsterBunny.prototype.constructor = MonsterBunny; - -/** - * Automatically called by World.update - */ -MonsterBunny.prototype.update = function() { - - this.angle += this.rotateSpeed; - -}; - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('bunny', 'assets/sprites/bunny.png'); - -} - -function create() { - - var wabbit = new MonsterBunny(game, 200, 300, 1); - wabbit.anchor.setTo(0.5, 0.5); - - var wabbit2 = new MonsterBunny(game, 600, 300, 0.5); - wabbit2.anchor.setTo(0.5, 0.5); - - game.add.existing(wabbit); - game.add.existing(wabbit2); - -} diff --git a/examples/sprites/extending sprite demo 2.js b/examples/sprites/extending sprite demo 2.js deleted file mode 100644 index 20a2583fb..000000000 --- a/examples/sprites/extending sprite demo 2.js +++ /dev/null @@ -1,45 +0,0 @@ - -MonsterBunny = function (game, rotateSpeed) { - - // We call the Phaser.Sprite passing in the game reference - // We're giving it a random X/Y position here, just for the sake of this demo - you could also pass the x/y in the constructor - Phaser.Sprite.call(this, game, game.world.randomX, game.world.randomY, 'bunny'); - - this.anchor.setTo(0.5, 0.5); - - this.rotateSpeed = rotateSpeed; - - var randomScale = 0.1 + Math.random(); - - this.scale.setTo(randomScale, randomScale) - - game.add.existing(this); - -}; - -MonsterBunny.prototype = Object.create(Phaser.Sprite.prototype); -MonsterBunny.prototype.constructor = MonsterBunny; - -MonsterBunny.prototype.update = function() { - - // Automatically called by World.update - this.angle += this.rotateSpeed; - -}; - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('bunny', 'assets/sprites/bunny.png'); - -} - -function create() { - - for (var i = 0.1; i < 2; i += 0.1) - { - new MonsterBunny(game, i); - } - -} diff --git a/examples/sprites/horizontal crop.js b/examples/sprites/horizontal crop.js deleted file mode 100644 index e3d2a9f25..000000000 --- a/examples/sprites/horizontal crop.js +++ /dev/null @@ -1,27 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update : update }); - -function preload() { - game.load.image('trsi', 'assets/pics/trsipic1_lazur.jpg'); -} - -var pic; -var cropRect; - -function create() { - - pic = game.add.sprite(game.world.centerX, 550, 'trsi'); - - pic.anchor.setTo(0.5, 1); - - cropRect = {x : 0, y : 0 , width : 0, height : pic.height}; - - // Here we'll tween the crop rect, from a width of zero to full width, and back again - game.add.tween(cropRect).to( { width: pic.width }, 3000, Phaser.Easing.Bounce.Out, true, 0, 1000, true); - -} - -function update () { - // the crop method takes a rectangle object as a parameter - pic.crop(cropRect); -} diff --git a/examples/sprites/move a sprite.js b/examples/sprites/move a sprite.js deleted file mode 100644 index ae1bdbc72..000000000 --- a/examples/sprites/move a sprite.js +++ /dev/null @@ -1,46 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - game.load.atlasJSONHash('bot', 'assets/sprites/running_bot.png', 'assets/sprites/running_bot.json'); -} - -var s; - -function create() { - - s = game.add.sprite(game.world.centerX, game.world.centerY, 'bot'); - s.anchor.setTo(0.5, 0.5); - s.scale.setTo(2, 2); - - s.animations.add('run'); - s.animations.play('run', 10, true); - -} - -function update() { - - if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - s.x -= 4; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - s.x += 4; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - s.y -= 4; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - s.y += 4; - } - -} - -function render() { - game.debug.spriteInfo(s, 20, 32); - -} diff --git a/examples/sprites/out of bounds.js b/examples/sprites/out of bounds.js deleted file mode 100644 index d781340ad..000000000 --- a/examples/sprites/out of bounds.js +++ /dev/null @@ -1,48 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('alien', 'assets/sprites/space-baddie.png'); - game.load.image('ship', 'assets/sprites/shmup-ship.png'); - -} - -var player; -var aliens; - -function create() { - - // We only want world bounds on the left and right - game.physics.setBoundsToWorld(); - - player = game.add.sprite(400, 500, 'ship'); - player.anchor.setTo(0.5, 0.5); - - aliens = game.add.group(); - aliens.enableBody = true; - aliens.physicsBodyType = Phaser.Physics.ARCADE; - - for (var y = 0; y < 4; y++) - { - for (var x = 0; x < 10; x++) - { - var alien = aliens.create(200 + x * 48, y * 50, 'alien'); - alien.name = 'alien' + x.toString() + y.toString(); - alien.checkWorldBounds = true; - alien.events.onOutOfBounds.add(alienOut, this); - alien.body.velocity.y = 50 + Math.random() * 200; - } - } - -} - -function alienOut(alien) { - - // Move the alien to the top of the screen again - alien.reset(alien.x, -32); - - // And give it a new random velocity - alien.body.velocity.y = 50 + Math.random() * 200; - -} diff --git a/examples/sprites/scale a sprite.js b/examples/sprites/scale a sprite.js deleted file mode 100644 index acf38dc23..000000000 --- a/examples/sprites/scale a sprite.js +++ /dev/null @@ -1,29 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create}); - -function preload() { - - game.load.image('disk', 'assets/sprites/darkwing_crazy.png'); - -} - -function create() { - - for (var i = 0; i < 15; i++) - { - // Create 15 sprites at random x/y locations - var sprite = game.add.sprite(game.world.randomX, game.world.randomY, 'disk'); - - // Pick a random number between -2 and 6 - var rand = game.rnd.realInRange(-2, 6); - - // Set the scale of the sprite to the random value - sprite.scale.setTo(rand, rand); - - // You can also scale sprites like this: - // sprite.scale.x = value; - // sprite.scale.y = value; - - } - -} diff --git a/examples/sprites/shared sprite textures.js b/examples/sprites/shared sprite textures.js deleted file mode 100644 index 294d0f0d6..000000000 --- a/examples/sprites/shared sprite textures.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - // We load a TexturePacker JSON file and image and show you how to make several unique sprites from the same file - game.load.atlas('atlas', 'assets/pics/texturepacker_test.png', 'assets/pics/texturepacker_test.json'); - -} - -var chick; -var car; -var mech; -var robot; -var cop; - -function create() { - - game.stage.backgroundColor = '#404040'; - - chick = game.add.sprite(64, 64, 'atlas'); - - // You can set the frame based on the frame name (which TexturePacker usually sets to be the filename of the image itself) - chick.frameName = 'budbrain_chick.png'; - - // Or by setting the frame index - //chick.frame = 0; - - cop = game.add.sprite(600, 64, 'atlas'); - cop.frameName = 'ladycop.png'; - - robot = game.add.sprite(50, 300, 'atlas'); - robot.frameName = 'robot.png'; - - car = game.add.sprite(100, 400, 'atlas'); - car.frameName = 'supercars_parsec.png'; - - mech = game.add.sprite(250, 100, 'atlas'); - mech.frameName = 'titan_mech.png'; - -} diff --git a/examples/sprites/sprite rotation.js b/examples/sprites/sprite rotation.js deleted file mode 100644 index 61ebab559..000000000 --- a/examples/sprites/sprite rotation.js +++ /dev/null @@ -1,37 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - game.load.image('arrow', 'assets/sprites/arrow.png'); -} - -var sprite; - -function create() { - - game.stage.backgroundColor = '#0072bc'; - - sprite = game.add.sprite(400, 300, 'arrow'); - sprite.anchor.setTo(0.5, 0.5); - -} - -function update() { - - sprite.angle += 1; - - // Note: Due to a bug in Chrome the following doesn't work atm: - // sprite.angle++; - // See: https://code.google.com/p/chromium/issues/detail?id=306851 - -} - -function render() { - - game.debug.spriteInfo(sprite, 32, 32); - // game.debug.text('angularVelocity: ' + sprite.body.angularVelocity, 32, 200); - // game.debug.text('angularAcceleration: ' + sprite.body.angularAcceleration, 32, 232); - // game.debug.text('angularDrag: ' + sprite.body.angularDrag, 32, 264); - // game.debug.text('deltaZ: ' + sprite.body.deltaZ(), 32, 296); - -} diff --git a/examples/sprites/spritesheet.js b/examples/sprites/spritesheet.js deleted file mode 100644 index 6039a2f3d..000000000 --- a/examples/sprites/spritesheet.js +++ /dev/null @@ -1,37 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -var sprite; - -function preload() { - - // 37x45 is the size of each frame - // There are 18 frames in the PNG - you can leave this value blank if the frames fill up the entire PNG, but in this case there are some - // blank frames at the end, so we tell the loader how many to load - game.load.spritesheet('ms', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -function create() { - - sprite = game.add.sprite(40, 100, 'ms'); - - sprite.animations.add('walk'); - - sprite.animations.play('walk', 50, true); - - game.add.tween(sprite).to({ x: game.width }, 10000, Phaser.Easing.Linear.None, true); - -} - -// update isn't called until 'create' has completed. If you need to process stuff before that point (i.e. while the preload is still happening) -// then create a function called loadUpdate() and use that -function update() { - - if (sprite.x >= 300) - { - sprite.scale.x += 0.01; - sprite.scale.y += 0.01; - } - -} diff --git a/examples/sprites/vertical crop.js b/examples/sprites/vertical crop.js deleted file mode 100644 index 5dd749be4..000000000 --- a/examples/sprites/vertical crop.js +++ /dev/null @@ -1,30 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create , update : update}); - -function preload() { - game.load.image('trsi', 'assets/pics/trsipic1_lazur.jpg'); -} - -var pic; -var cropRect; - -function create() { - - pic = game.add.sprite(game.world.centerX, 550, 'trsi'); - - pic.anchor.setTo(0.5, 1); - - - cropRect = {x : 0, y : 0 , width : pic.width, height : 0}; - - // Here we'll tween the crop rect, from a height of zero to full height, and back again - game.add.tween(cropRect).to( { height: pic.height }, 3000, Phaser.Easing.Bounce.Out, true, 0, 1000, true); - -} - -function update () { - // the crop method takes a rectangle object as a parameter - pic.crop(cropRect); -} - - diff --git a/examples/text/bitmap fonts.js b/examples/text/bitmap fonts.js deleted file mode 100644 index 267f26204..000000000 --- a/examples/text/bitmap fonts.js +++ /dev/null @@ -1,22 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.bitmapFont('desyrel', 'assets/fonts/bitmapFonts/desyrel.png', 'assets/fonts/bitmapFonts/desyrel.xml'); - -} - -var bpmText; - -function create() { - - bmpText = game.add.bitmapText(200, 100, 'desyrel','Phaser & Pixi \nrocking!',64); - -} - -function update() { - - bmpText.setText('Phaser & Pixi\nrocking!\n' + Math.round(game.time.now)); - -} diff --git a/examples/text/bitmapfont drag.js b/examples/text/bitmapfont drag.js deleted file mode 100644 index 94a290372..000000000 --- a/examples/text/bitmapfont drag.js +++ /dev/null @@ -1,21 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.bitmapFont('carrier_command', 'assets/fonts/bitmapFonts/carrier_command.png', 'assets/fonts/bitmapFonts/carrier_command.xml'); - -} - -var bpmText; - -function create() { - - bmpText = game.add.bitmapText(10, 100, 'carrier_command','Drag me around !',34); - - bmpText.inputEnabled = true; - - bmpText.input.enableDrag(); - -} - diff --git a/examples/text/dynamic text shadow.js b/examples/text/dynamic text shadow.js deleted file mode 100644 index c959c1e49..000000000 --- a/examples/text/dynamic text shadow.js +++ /dev/null @@ -1,49 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, update: update }); - -var text; - -function create() { - - game.stage.setBackgroundColor(0xfbf6d5); - - text = game.add.text(game.world.centerX, 250, ' dynamic shadows '); - text.anchor.set(0.5); - text.align = 'center'; - - text.font = 'Arial Black'; - text.fontSize = 70; - text.fontWeight = 'bold'; - text.fill = '#ec008c'; - - text.setShadow(0, 0, 'rgba(0, 0, 0, 0.5)', 0); - -} - -function update() { - - var offset = moveToXY(game.input.activePointer, text.x, text.y, 8); - - text.setShadow(offset.x, offset.y, 'rgba(0, 0, 0, 0.5)', distanceToPointer(text, game.input.activePointer) / 30); - -} - -function distanceToPointer(displayObject, pointer) { - - this._dx = displayObject.x - pointer.x; - this._dy = displayObject.y - pointer.y; - - return Math.sqrt(this._dx * this._dx + this._dy * this._dy); - -} - -function moveToXY(displayObject, x, y, speed) { - - var _angle = Math.atan2(y - displayObject.y, x - displayObject.x); - - var x = Math.cos(_angle) * speed; - var y = Math.sin(_angle) * speed; - - return { x: x, y: y }; - -} diff --git a/examples/text/google webfonts.js b/examples/text/google webfonts.js deleted file mode 100644 index 814f75411..000000000 --- a/examples/text/google webfonts.js +++ /dev/null @@ -1,72 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create }); - -// The Google WebFont Loader will look for this object, so create it before loading the script. -WebFontConfig = { - - // 'active' means all requested fonts have finished loading - // We set a 1 second delay before calling 'createText'. - // For some reason if we don't the browser cannot render the text the first time it's created. - active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); }, - - // The Google Fonts we want to load (specify as many as you like in the array) - google: { - families: ['Revalia'] - } - -}; - -function preload() { - - // Load the Google WebFont Loader script - game.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js'); - -} - -var text = null; -var grd; - -function create() { - - game.stage.setBackgroundColor(0x2d2d2d); - -} - -function createText() { - - text = game.add.text(game.world.centerX, game.world.centerY, "- phaser -\nrocking with\ngoogle web fonts"); - text.anchor.setTo(0.5); - - text.font = 'Revalia'; - text.fontSize = 60; - - // x0, y0 - x1, y1 - grd = text.context.createLinearGradient(0, 0, 0, text.canvas.height); - grd.addColorStop(0, '#8ED6FF'); - grd.addColorStop(1, '#004CB3'); - text.fill = grd; - - text.align = 'center'; - text.stroke = '#000000'; - text.strokeThickness = 2; - text.setShadow(5, 5, 'rgba(0,0,0,0.5)', 5); - - text.inputEnabled = true; - text.input.enableDrag(); - - text.events.onInputOver.add(over, this); - text.events.onInputOut.add(out, this); - -} - -function out() { - - text.fill = grd; - -} - -function over() { - - text.fill = '#ff00ff'; - -} diff --git a/examples/text/hello arial.js b/examples/text/hello arial.js deleted file mode 100644 index f1e7dd152..000000000 --- a/examples/text/hello arial.js +++ /dev/null @@ -1,10 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - -function create() { - - var style = { font: "65px Arial", fill: "#ff0044", align: "center" }; - var text = game.add.text(game.world.centerX, game.world.centerY, "- phaser -\nwith a sprinkle of\npixi dust", style); - - text.anchor.set(0.5); - -} \ No newline at end of file diff --git a/examples/text/kern of duty.js b/examples/text/kern of duty.js deleted file mode 100644 index 5d0d6d868..000000000 --- a/examples/text/kern of duty.js +++ /dev/null @@ -1,62 +0,0 @@ - -var game = new Phaser.Game(800, 480, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -var content = [ - " ", - "photon storm presents", - "a phaser production", - " ", - "Kern of Duty", - " ", - "directed by rich davey", - "rendering by mat groves", - " ", - "03:45, November 4th, 2014", - "somewhere in the north pacific", - "mission control bravo ...", -]; - -var t = 0; -var s; -var index = 0; -var line = ''; - -function preload() { - game.load.image('cod', 'assets/pics/cod.jpg'); -} - -function create() { - - game.add.sprite(0, 0, 'cod'); - - var style = { font: "30pt Courier", fill: "#19cb65", stroke: "#119f4e", strokeThickness: 2 }; - - s = game.add.text(32, 380, '', style); - t = game.time.now + 80; - -} - -function update() { - - if (game.time.now > t && index < content.length) - { - // get the next character in the line - if (line.length < content[index].length) - { - line = content[index].substr(0, line.length + 1); - s.setText(line); - t = game.time.now + 80; - } - else - { - t = game.time.now + 2000; - - if (index < content.length) - { - index++; - line = ''; - } - } - } - -} diff --git a/examples/text/littera.js b/examples/text/littera.js deleted file mode 100644 index a2cacf457..000000000 --- a/examples/text/littera.js +++ /dev/null @@ -1,14 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.bitmapFont('shortStack', 'assets/fonts/bitmapFonts/shortStack.png', 'assets/fonts/bitmapFonts/shortStack.fnt'); - -} - -function create() { - - game.add.bitmapText(32, 32, 'shortStack', 'This font was generated using the\nfree Littera web site\n\nhttp://kvazars.com/littera/', 32); - -} diff --git a/examples/text/remove text.js b/examples/text/remove text.js deleted file mode 100644 index dd58c1d33..000000000 --- a/examples/text/remove text.js +++ /dev/null @@ -1,19 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - -var text; - -function create() { - - text = game.add.text(game.world.centerX, game.world.centerY, "- phaser -\nclick to remove", { font: "65px Arial", fill: "#ff0044", align: "center" }); - text.anchor.setTo(0.5, 0.5); - - game.input.onDown.addOnce(removeText, this); - -} - -function removeText() { - - text.destroy(); - -} diff --git a/examples/text/retro font 1.js b/examples/text/retro font 1.js deleted file mode 100644 index 5f199adc9..000000000 --- a/examples/text/retro font 1.js +++ /dev/null @@ -1,30 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('knightHawks', 'assets/fonts/retroFonts/KNIGHT3.png'); - -} - -var font; - -function create() { - - font = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET6, 10, 1, 1); - font.text = 'phaser was here'; - - for (var c = 0; c < 19; c++) - { - var i = game.add.image(game.world.centerX, c * 32, font); - i.tint = Math.random() * 0xFFFFFF; - i.anchor.set(0.5, 1); - } - -} - -function update() { - - font.text = "phaser x: " + game.input.x + " y: " + game.input.y; - -} diff --git a/examples/text/retro font 2.js b/examples/text/retro font 2.js deleted file mode 100644 index fc6f23b0a..000000000 --- a/examples/text/retro font 2.js +++ /dev/null @@ -1,47 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('goldFont', 'assets/fonts/retroFonts/gold_font.png'); - game.load.image('bluePink', 'assets/fonts/retroFonts/bluepink_font.png'); - game.load.image('forgotten', 'assets/pics/forgotten_worlds.png'); - -} - -var font1; -var font2; -var image1; -var image2; - -function create() { - - font1 = game.add.retroFont('goldFont', 16, 16, "! :() ,?." + Phaser.RetroFont.TEXT_SET10, 20, 0, 0); - font1.text = "phaser brings you retro style bitmap fonts"; - - image1 = game.add.image(game.world.centerX, 48, font1); - image1.anchor.set(0.5); - - font2 = game.add.retroFont('bluePink', 32, 32, Phaser.RetroFont.TEXT_SET2, 10); - font2.setText("phaser 2\nin the house", true, 0, 8, Phaser.RetroFont.ALIGN_CENTER); - - image2 = game.add.image(game.world.centerX, 220, font2); - image2.anchor.set(0.5); - - game.add.image(0, game.height - 274, 'forgotten'); - - game.time.events.loop(Phaser.Timer.SECOND * 2, change, this); - -} - -function change() { - - image2.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - image2.rotation += (2 * game.time.physicsElapsed); - -} diff --git a/examples/text/set properties after creation.js b/examples/text/set properties after creation.js deleted file mode 100644 index f969b1521..000000000 --- a/examples/text/set properties after creation.js +++ /dev/null @@ -1,29 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.bitmapFont('desyrel', 'assets/fonts/bitmapFonts/desyrel.png', 'assets/fonts/bitmapFonts/desyrel.xml'); - -} - -var bpmText; -var count = 0; - -function create() { - - bmpText = game.add.bitmapText(0, 100, 'desyrel',"I'm growing",64); - -} - -function update() { - - count++; - - if(bmpText.fontSize < 250){ - bmpText.fontSize += 1; - } - - - -} diff --git a/examples/text/text gradient.js b/examples/text/text gradient.js deleted file mode 100644 index b5af2a195..000000000 --- a/examples/text/text gradient.js +++ /dev/null @@ -1,30 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - -var text = null; - -function create() { - - text = game.add.text(game.world.centerX, game.world.centerY, "- phaser gradient text -"); - - // Centers the text - text.anchor.set(0.5); - text.align = 'center'; - - // Our font + size - text.font = 'Arial'; - text.fontWeight = 'bold'; - text.fontSize = 70; - - // Here we create a linear gradient on the Text context. - // This uses the exact same method of creating a gradient as you do on a normal Canvas context. - var grd = text.context.createLinearGradient(0, 0, 0, text.canvas.height); - - // Add in 2 color stops - grd.addColorStop(0, '#8ED6FF'); - grd.addColorStop(1, '#004CB3'); - - // And apply to the Text - text.fill = grd; - -} diff --git a/examples/text/text reflect.js b/examples/text/text reflect.js deleted file mode 100644 index 9b17136f2..000000000 --- a/examples/text/text reflect.js +++ /dev/null @@ -1,49 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - -var text = null; -var textReflect = null; - -function create() { - - game.stage.backgroundColor = 0x3b0760; - - text = game.add.text(game.world.centerX, game.world.centerY, "- PHASER -"); - - // Centers the text - text.anchor.set(0.5); - text.align = 'center'; - - // Our font + size - text.font = 'Arial'; - text.fontWeight = 'bold'; - text.fontSize = 70; - text.fill = '#ffffff'; - - // Here we create our fake reflection :) - // It's just another Text object, with an alpha gradient and flipped vertically - - textReflect = game.add.text(game.world.centerX, game.world.centerY + 50, "- PHASER -"); - - // Centers the text - textReflect.anchor.set(0.5); - textReflect.align = 'center'; - textReflect.scale.y = -1; - - // Our font + size - textReflect.font = 'Arial'; - textReflect.fontWeight = 'bold'; - textReflect.fontSize = 70; - - // Here we create a linear gradient on the Text context. - // This uses the exact same method of creating a gradient as you do on a normal Canvas context. - var grd = textReflect.context.createLinearGradient(0, 0, 0, text.canvas.height); - - // Add in 2 color stops - grd.addColorStop(0, 'rgba(255,255,255,0)'); - grd.addColorStop(1, 'rgba(255,255,255,0.08)'); - - // And apply to the Text - textReflect.fill = grd; - -} diff --git a/examples/text/text shadow.js b/examples/text/text shadow.js deleted file mode 100644 index 3405a71ca..000000000 --- a/examples/text/text shadow.js +++ /dev/null @@ -1,42 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, update: update }); - -function create() { - - game.stage.setBackgroundColor(0xefefef); - - // Here we set the shadow: - // The first 2 parameters control x and y distance - // The 3rd the shadow colour - // The 4th the amount of blur - - var text = createText(100, 'shadow 5'); - text.setShadow(3, 3, 'rgba(0,0,0,0.5)', 5); - - text = createText(300, 'shadow 0'); - text.setShadow(5, 5, 'rgba(0,0,0,0.5)', 15); - - text = createText(500, 'shadow 10'); - text.setShadow(-5, 5, 'rgba(0,0,0,0.5)', 0); - -} - -function createText(y) { - - var text = game.add.text(game.world.centerX, y, '- phaser text shadow -'); - text.anchor.set(0.5); - text.align = 'center'; - - // Font style - text.font = 'Arial Black'; - text.fontSize = 50; - text.fontWeight = 'bold'; - text.fill = '#ff00ff'; - - return text; - -} - -function update() { - -} diff --git a/examples/text/text stroke.js b/examples/text/text stroke.js deleted file mode 100644 index d1a4cd0ab..000000000 --- a/examples/text/text stroke.js +++ /dev/null @@ -1,32 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, update: update }); - -var text; - -function create() { - - game.stage.setBackgroundColor(0x2d2d2d); - - text = game.add.text(game.world.centerX, game.world.centerY, '- phaser text stroke -'); - - // Center align - text.anchor.set(0.5); - text.align = 'center'; - - // Font style - text.font = 'Arial Black'; - text.fontSize = 50; - text.fontWeight = 'bold'; - - // Stroke color and thickness - text.stroke = '#000000'; - text.strokeThickness = 6; - text.fill = '#43d637'; - -} - -function update() { - - // text.angle += 1; - -} diff --git a/examples/text/update text.js b/examples/text/update text.js deleted file mode 100644 index 7b1a51442..000000000 --- a/examples/text/update text.js +++ /dev/null @@ -1,35 +0,0 @@ -// Example created by Arlefreak (https://github.com/Arlefreak) - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, update: update }); - -var text; -var count; - -function create() { - - count = 0; - - text = game.add.text(game.world.centerX, game.world.centerY, "- You have clicked -\n0 times !", { - font: "65px Arial", - fill: "#ff0044", - align: "center" - }); - - text.anchor.setTo(0.5, 0.5); - -} - -function update() { - - game.input.onDown.addOnce(updateText, this); - -} - - -function updateText() { - - count++; - - text.setText("- You have clicked -\n" + count + " times !"); - -} \ No newline at end of file diff --git a/examples/tile sprites/animated tiling sprite.js b/examples/tile sprites/animated tiling sprite.js deleted file mode 100644 index 21989bbca..000000000 --- a/examples/tile sprites/animated tiling sprite.js +++ /dev/null @@ -1,48 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - game.load.image('disk', 'assets/sprites/p2.jpeg'); -} - -var tilesprite; -var cursors; -var count = 0; - -function create() { - - tilesprite = game.add.tileSprite(0, 0, 512, 512, 'disk'); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - count += 0.005 - - tilesprite.tileScale.x = 2 + Math.sin(count); - tilesprite.tileScale.y = 2 + Math.cos(count); - - tilesprite.tilePosition.x += 1; - tilesprite.tilePosition.y += 1; - - if (cursors.left.isDown) - { - tilesprite.x -= 4; - } - else if (cursors.right.isDown) - { - tilesprite.x += 4; - } - - if (cursors.up.isDown) - { - tilesprite.y -= 4; - } - else if (cursors.down.isDown) - { - tilesprite.y += 4; - } - -} diff --git a/examples/tile sprites/colliding with tiling sprite.js b/examples/tile sprites/colliding with tiling sprite.js deleted file mode 100644 index f14266a8e..000000000 --- a/examples/tile sprites/colliding with tiling sprite.js +++ /dev/null @@ -1,72 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -var ball; -var tilesprite; -var cursors; - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.image('ball', 'assets/sprites/pangball.png'); - -} - -function create() { - - game.physics.arcade.gravity.y = 20; - - ball = game.add.sprite(400, 0, 'ball'); - - - - - game.physics.enable(ball, Phaser.Physics.ARCADE); - - tilesprite = game.add.tileSprite(300, 450, 200, 100, 'starfield'); - - - - game.physics.enable(tilesprite, Phaser.Physics.ARCADE); - - - ball.body.collideWorldBounds = true; - - tilesprite.body.collideWorldBounds = true; - - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.arcade.collide(ball,tilesprite); - - if (cursors.left.isDown) - { - tilesprite.x -= 8; - tilesprite.tilePosition.x -= 8; - } - else if (cursors.right.isDown) - { - tilesprite.x += 8; - tilesprite.tilePosition.x += 8; - } - - if (cursors.up.isDown) - { - tilesprite.tilePosition.y += 8; - } - else if (cursors.down.isDown) - { - tilesprite.tilePosition.y -= 8; - } - -} - -function render() { - - // game.debug.physicsBody(tilesprite); - -} \ No newline at end of file diff --git a/examples/tile sprites/tiling sprite.js b/examples/tile sprites/tiling sprite.js deleted file mode 100644 index 89e671f35..000000000 --- a/examples/tile sprites/tiling sprite.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -var tilesprite; -var cursors; - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - -} - -function create() { - - tilesprite = game.add.tileSprite(0, 0, 800, 600, 'starfield'); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - tilesprite.tilePosition.x += 8; - } - else if (cursors.right.isDown) - { - tilesprite.tilePosition.x -= 8; - } - - if (cursors.up.isDown) - { - tilesprite.tilePosition.y += 8; - } - else if (cursors.down.isDown) - { - tilesprite.tilePosition.y -= 8; - } - -} diff --git a/examples/tilemaps/blank tilemap.js b/examples/tilemaps/blank tilemap.js deleted file mode 100644 index 7df91df5f..000000000 --- a/examples/tilemaps/blank tilemap.js +++ /dev/null @@ -1,113 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - -} - -var map; -var layer; - -var marker; -var currentTile = 0; -var cursors; - -function create() { - - game.stage.backgroundColor = '#787878'; - - // Creates a blank tilemap - map = game.add.tilemap(); - - // Creates a layer and sets-up the map dimensions. - // In this case the map is 30x30 tiles in size and the tiles are 32x32 pixels in size. - map.create('level1', 30, 30, 32, 32); - - // Add a Tileset image to the map - map.addTilesetImage('ground_1x1'); - - // Create a layer. This is where the map is rendered to. - layer = map.createLayer('level1'); - - // Resize the world - layer.resizeWorld(); - - // Create our tile selector at the top of the screen - createTileSelector(); - - game.input.setMoveCallback(updateMarker, this); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function pickTile(sprite, pointer) { - - currentTile = game.math.snapToFloor(pointer.x, 32) / 32; - -} - -function updateMarker() { - - marker.x = layer.getTileX(game.input.activePointer.worldX) * 32; - marker.y = layer.getTileY(game.input.activePointer.worldY) * 32; - - if (game.input.mousePointer.isDown) - { - map.putTile(currentTile, layer.getTileX(marker.x), layer.getTileY(marker.y)) - } - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - -} - -function render() { - -} - -function createTileSelector() { - - // Our tile selection window - var tileSelector = game.add.group(); - - var tileSelectorBackground = game.make.graphics(); - tileSelectorBackground.beginFill(0x000000, 0.5); - tileSelectorBackground.drawRect(0, 0, 800, 34); - tileSelectorBackground.endFill(); - - tileSelector.add(tileSelectorBackground); - - var tileStrip = tileSelector.create(1, 1, 'ground_1x1'); - tileStrip.inputEnabled = true; - tileStrip.events.onInputDown.add(pickTile, this); - - tileSelector.fixedToCamera = true; - - // Our painting marker - marker = game.add.graphics(); - marker.lineStyle(2, 0x000000, 1); - marker.drawRect(0, 0, 32, 32); - -} \ No newline at end of file diff --git a/examples/tilemaps/create from objects.js b/examples/tilemaps/create from objects.js deleted file mode 100644 index 879a5351c..000000000 --- a/examples/tilemaps/create from objects.js +++ /dev/null @@ -1,106 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/features_test.json', null, Phaser.Tilemap.TILED_JSON); - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('walls_1x2', 'assets/tilemaps/tiles/walls_1x2.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - - game.load.image('phaser', 'assets/sprites/arrow.png'); - game.load.spritesheet('coin', 'assets/sprites/coin.png', 32, 32); - -} - -var cursors; -var map; -var coins; - -var layer; -var sprite; - -function create() { - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('walls_1x2'); - map.addTilesetImage('tiles2'); - - map.setCollisionBetween(1, 12); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - game.physics.startSystem(Phaser.Physics.ARCADE); - - // Here we create our coins group - coins = game.add.group(); - coins.enableBody = true; - - // And now we convert all of the Tiled objects with an ID of 34 into sprites within the coins group - map.createFromObjects('Object Layer 1', 34, 'coin', 0, true, false, coins); - - // Add animations to all of the coin sprites - coins.callAll('animations.add', 'animations', 'spin', [0, 1, 2, 3, 4, 5], 10, true); - coins.callAll('animations.play', 'animations', 'spin'); - - sprite = game.add.sprite(260, 100, 'phaser'); - sprite.anchor.set(0.5); - - game.physics.arcade.enable(sprite); - - // This adjusts the collision body size. - sprite.body.setSize(32, 32, 16, 16); - - // We'll set a lower max angular velocity here to keep it from going totally nuts - sprite.body.maxAngular = 500; - - // Apply a drag otherwise the sprite will just spin and never slow down - sprite.body.angularDrag = 50; - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - game.physics.arcade.overlap(sprite, coins, collectCoin, null, this); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -300; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 300; - } - - if (cursors.up.isDown) - { - game.physics.arcade.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - -} - -function collectCoin(player, coin) { - - coin.kill(); - -} - -function render() { - - game.debug.body(sprite); - -} \ No newline at end of file diff --git a/examples/tilemaps/csv map.js b/examples/tilemaps/csv map.js deleted file mode 100644 index ffa781667..000000000 --- a/examples/tilemaps/csv map.js +++ /dev/null @@ -1,61 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/csv/catastrophi_level2.csv', null, Phaser.Tilemap.CSV); - game.load.image('tiles', 'assets/tilemaps/tiles/catastrophi_tiles_16.png'); - -} - -var map; -var layer; -var cursors; - -function create() { - - // Because we're loading CSV map data we have to specify the tile size here or we can't render it - map = game.add.tilemap('map', 16, 16); - - // Now add in the tileset - map.addTilesetImage('tiles'); - - // Create our layer - layer = map.createLayer(0); - - // Resize the world - layer.resizeWorld(); - - // Allow cursors to scroll around the map - cursors = game.input.keyboard.createCursorKeys(); - - var help = game.add.text(16, 16, 'Arrows to scroll', { font: '14px Arial', fill: '#ffffff' }); - help.fixedToCamera = true; - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - -} - -function render() { - -} diff --git a/examples/tilemaps/fill tiles.js b/examples/tilemaps/fill tiles.js deleted file mode 100644 index 8807782cb..000000000 --- a/examples/tilemaps/fill tiles.js +++ /dev/null @@ -1,79 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('desert', 'assets/tilemaps/maps/desert.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/tmw_desert_spacing.png'); - game.load.image('car', 'assets/sprites/car90.png'); - -} - -var map; -var layer; - -var cursors; -var sprite; - -function create() { - - game.physics.startSystem(Phaser.Physics.ARCADE); - - map = game.add.tilemap('desert'); - - map.addTilesetImage('Desert', 'tiles'); - - layer = map.createLayer('Ground'); - - layer.resizeWorld(); - - sprite = game.add.sprite(450, 80, 'car'); - sprite.anchor.setTo(0.5, 0.5); - - game.physics.enable(sprite); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.add(fillTiles, this); - -} - -function fillTiles() { - - map.fill(31, layer.getTileX(sprite.x), layer.getTileY(sprite.y), 8, 8); - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -200; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 200; - } - - if (cursors.up.isDown) - { - sprite.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(sprite.angle, 300)); - } - -} - -function render() { - - game.debug.text('Click to fill tiles', 32, 32, 'rgb(0,0,0)'); - game.debug.text('Tile X: ' + layer.getTileX(sprite.x), 32, 48, 'rgb(0,0,0)'); - game.debug.text('Tile Y: ' + layer.getTileY(sprite.y), 32, 64, 'rgb(0,0,0)'); - -} diff --git a/examples/tilemaps/map bounce.js b/examples/tilemaps/map bounce.js deleted file mode 100644 index 3c34346f2..000000000 --- a/examples/tilemaps/map bounce.js +++ /dev/null @@ -1,78 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - -} - -var map; -var layer; -var cursors; -var sprite; - -function create() { - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - map.setCollisionBetween(1, 12); - - // layer.debug = true; - - sprite = game.add.sprite(260, 70, 'phaser'); - - game.physics.enable(sprite); - - sprite.body.bounce.set(0.8); - sprite.body.tilePadding.set(32); - - game.camera.follow(sprite); - - game.physics.arcade.gravity.y = 200; - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - - // Un-comment these to gain full control over the sprite - // sprite.body.velocity.x = 0; - // sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - } - -} - -function render() { - - // game.debug.body(sprite); - -} diff --git a/examples/tilemaps/map collide.js b/examples/tilemaps/map collide.js deleted file mode 100644 index 95e55a5fd..000000000 --- a/examples/tilemaps/map collide.js +++ /dev/null @@ -1,89 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('mario', 'assets/tilemaps/maps/super_mario.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/super_mario.png'); - game.load.image('player', 'assets/sprites/phaser-dude.png'); - -} - -var map; -var tileset; -var layer; -var p; -var cursors; - -function create() { - - game.physics.startSystem(Phaser.Physics.ARCADE); - - game.stage.backgroundColor = '#787878'; - - map = game.add.tilemap('mario'); - - map.addTilesetImage('SuperMarioBros-World1-1', 'tiles'); - - // 14 = ? block - // map.setCollisionBetween(14, 15); - - map.setCollisionBetween(15, 16); - map.setCollisionBetween(20, 25); - map.setCollisionBetween(27, 29); - map.setCollision(40); - - layer = map.createLayer('World1'); - - // Un-comment this on to see the collision tiles - // layer.debug = true; - - layer.resizeWorld(); - - p = game.add.sprite(32, 32, 'player'); - - game.physics.enable(p); - - game.physics.arcade.gravity.y = 250; - - p.body.bounce.y = 0.2; - p.body.linearDamping = 1; - p.body.collideWorldBounds = true; - - game.camera.follow(p); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.arcade.collide(p, layer); - - p.body.velocity.x = 0; - - if (cursors.up.isDown) - { - if (p.body.onFloor()) - { - p.body.velocity.y = -200; - } - } - - if (cursors.left.isDown) - { - p.body.velocity.x = -150; - } - else if (cursors.right.isDown) - { - p.body.velocity.x = 150; - } - -} - -function render() { - - // game.debug.body(p); - game.debug.bodyInfo(p, 32, 320); - -} diff --git a/examples/tilemaps/paint tiles.js b/examples/tilemaps/paint tiles.js deleted file mode 100644 index 2c06f6ba6..000000000 --- a/examples/tilemaps/paint tiles.js +++ /dev/null @@ -1,82 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('desert', 'assets/tilemaps/maps/desert.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/tmw_desert_spacing.png'); - -} - -var map; -var layer; - -var marker; -var currentTile; -var cursors; - -function create() { - - map = game.add.tilemap('desert'); - - map.addTilesetImage('Desert', 'tiles'); - - currentTile = map.getTile(2, 3); - - layer = map.createLayer('Ground'); - - layer.resizeWorld(); - - marker = game.add.graphics(); - marker.lineStyle(2, 0x000000, 1); - marker.drawRect(0, 0, 32, 32); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - marker.x = layer.getTileX(game.input.activePointer.worldX) * 32; - marker.y = layer.getTileY(game.input.activePointer.worldY) * 32; - - if (game.input.mousePointer.isDown) - { - if (game.input.keyboard.isDown(Phaser.Keyboard.SHIFT)) - { - currentTile = map.getTile(layer.getTileX(marker.x), layer.getTileY(marker.y)); - } - else - { - if (map.getTile(layer.getTileX(marker.x), layer.getTileY(marker.y)) != currentTile) - { - map.putTile(currentTile, layer.getTileX(marker.x), layer.getTileY(marker.y)) - } - } - } - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - -} - -function render() { - - game.debug.text('Left-click to paint. Shift + Left-click to select tile. Arrows to scroll.', 32, 32, '#efefef'); - -} diff --git a/examples/tilemaps/randomise tiles.js b/examples/tilemaps/randomise tiles.js deleted file mode 100644 index 36abe4466..000000000 --- a/examples/tilemaps/randomise tiles.js +++ /dev/null @@ -1,85 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('desert', 'assets/tilemaps/maps/desert.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/tmw_desert_spacing.png'); - game.load.image('car', 'assets/sprites/car90.png'); - -} - -var map; -var layer; - -var cursors; -var sprite; -var marker; - -function create() { - - game.physics.startSystem(Phaser.Physics.ARCADE); - - map = game.add.tilemap('desert'); - - map.addTilesetImage('Desert', 'tiles'); - - layer = map.createLayer('Ground'); - - layer.resizeWorld(); - - marker = game.add.graphics(); - marker.lineStyle(2, 0x00bff3, 1); - marker.drawRect(0, 0, 32 * 6, 32 * 6); - - sprite = game.add.sprite(450, 80, 'car'); - sprite.anchor.setTo(0.5, 0.5); - - game.physics.enable(sprite); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.add(randomiseTiles, this); - -} - -function randomiseTiles() { - - map.random(layer.getTileX(sprite.x), layer.getTileY(sprite.y), 6, 6); - -} - -function update() { - - marker.x = layer.getTileX(sprite.x) * 32; - marker.y = layer.getTileY(sprite.y) * 32; - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -200; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 200; - } - - if (cursors.up.isDown) - { - sprite.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(sprite.angle, 300)); - } - -} - -function render() { - - game.debug.text('Click to randomise tiles', 32, 32, 'rgb(0,0,0)'); - game.debug.text('Tile X: ' + layer.getTileX(sprite.x), 32, 48, 'rgb(0,0,0)'); - game.debug.text('Tile Y: ' + layer.getTileY(sprite.y), 32, 64, 'rgb(0,0,0)'); - -} diff --git a/examples/tilemaps/replace tiles.js b/examples/tilemaps/replace tiles.js deleted file mode 100644 index 79a0c0618..000000000 --- a/examples/tilemaps/replace tiles.js +++ /dev/null @@ -1,82 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('desert', 'assets/tilemaps/maps/desert.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/tmw_desert_spacing.png'); - game.load.image('car', 'assets/sprites/car90.png'); - -} - -var map; -var layer; - -var cursors; -var sprite; - -function create() { - - game.physics.startSystem(Phaser.Physics.ARCADE); - - map = game.add.tilemap('desert'); - - map.addTilesetImage('Desert', 'tiles'); - - layer = map.createLayer('Ground'); - - layer.resizeWorld(); - - sprite = game.add.sprite(450, 80, 'car'); - sprite.anchor.setTo(0.5, 0.5); - - game.physics.enable(sprite); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.addOnce(replaceTiles, this); - -} - -function replaceTiles() { - - // This will replace every instance of tile 31 (cactus plant) with tile 46 (the sign post). - // It does this across the whole layer of the map unless a region is specified. - - // You can also pass in x, y, width, height values to control the area in which the replace happens - - map.replace(31, 46); - -} - -function update() { - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -200; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 200; - } - - if (cursors.up.isDown) - { - sprite.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(sprite.angle, 300)); - } - -} - -function render() { - - game.debug.text('Click to replace tiles', 32, 32, 'rgb(0,0,0)'); - game.debug.text('Tile X: ' + layer.getTileX(sprite.x), 32, 48, 'rgb(0,0,0)'); - game.debug.text('Tile Y: ' + layer.getTileY(sprite.y), 32, 64, 'rgb(0,0,0)'); - -} diff --git a/examples/tilemaps/sci fly.js b/examples/tilemaps/sci fly.js deleted file mode 100644 index 5372b1f00..000000000 --- a/examples/tilemaps/sci fly.js +++ /dev/null @@ -1,104 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level3', 'assets/tilemaps/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/cybernoid.png', 16, 16); - game.load.image('phaser', 'assets/sprites/phaser-ship.png'); - game.load.image('chunk', 'assets/sprites/chunk.png'); - -} - -var map; -var layer; -var cursors; -var sprite; -var emitter; - -function create() { - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = game.add.tilemap('level3'); - - map.addTilesetImage('CybernoidMap3BG_bank.png', 'tiles'); - - layer = map.createLayer(0); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - map.setCollisionByExclusion([7, 32, 35, 36, 47]); - - layer.resizeWorld(); - - cursors = game.input.keyboard.createCursorKeys(); - - emitter = game.add.emitter(0, 0, 200); - - emitter.makeParticles('chunk'); - emitter.minRotation = 0; - emitter.maxRotation = 0; - emitter.gravity = 150; - emitter.bounce.setTo(0.5, 0.5); - - sprite = game.add.sprite(300, 90, 'phaser'); - sprite.anchor.set(0.5); - - game.physics.enable(sprite); - - // Because both our body and our tiles are so tiny, - // and the body is moving pretty fast, we need to add - // some tile padding to the body. WHat this does - sprite.body.tilePadding.set(32, 32); - - game.camera.follow(sprite); - -} - -function particleBurst() { - - emitter.x = sprite.x; - emitter.y = sprite.y; - emitter.start(true, 2000, null, 1); - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - game.physics.arcade.collide(emitter, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - particleBurst(); - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - particleBurst(); - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - sprite.scale.x = -1; - particleBurst(); - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - sprite.scale.x = 1; - particleBurst(); - } - -} - -function render() { - - // game.debug.body(sprite); - -} diff --git a/examples/tilemaps/shuffle tiles.js b/examples/tilemaps/shuffle tiles.js deleted file mode 100644 index fad8371f5..000000000 --- a/examples/tilemaps/shuffle tiles.js +++ /dev/null @@ -1,85 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('desert', 'assets/tilemaps/maps/desert.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/tmw_desert_spacing.png'); - game.load.image('car', 'assets/sprites/car90.png'); - -} - -var map; -var layer; - -var cursors; -var sprite; -var marker; - -function create() { - - game.physics.startSystem(Phaser.Physics.ARCADE); - - map = game.add.tilemap('desert'); - - map.addTilesetImage('Desert', 'tiles'); - - layer = map.createLayer('Ground'); - - layer.resizeWorld(); - - marker = game.add.graphics(); - marker.lineStyle(2, 0x00bff3, 1); - marker.drawRect(0, 0, 32 * 6, 32 * 6); - - sprite = game.add.sprite(450, 80, 'car'); - sprite.anchor.setTo(0.5, 0.5); - - game.physics.enable(sprite); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.add(randomiseTiles, this); - -} - -function randomiseTiles() { - - map.shuffle(layer.getTileX(sprite.x), layer.getTileY(sprite.y), 6, 6); - -} - -function update() { - - marker.x = layer.getTileX(sprite.x) * 32; - marker.y = layer.getTileY(sprite.y) * 32; - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -200; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 200; - } - - if (cursors.up.isDown) - { - sprite.body.velocity.copyFrom(game.physics.arcade.velocityFromAngle(sprite.angle, 300)); - } - -} - -function render() { - - game.debug.text('Click to randomise tiles', 32, 32, 'rgb(0,0,0)'); - game.debug.text('Tile X: ' + layer.getTileX(sprite.x), 32, 48, 'rgb(0,0,0)'); - game.debug.text('Tile Y: ' + layer.getTileY(sprite.y), 32, 64, 'rgb(0,0,0)'); - -} diff --git a/examples/tilemaps/swap tiles.js b/examples/tilemaps/swap tiles.js deleted file mode 100644 index e2510e1a9..000000000 --- a/examples/tilemaps/swap tiles.js +++ /dev/null @@ -1,78 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('desert', 'assets/tilemaps/maps/desert.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/tmw_desert_spacing.png'); - game.load.image('car', 'assets/sprites/car90.png'); - -} - -var map; -var layer; - -var cursors; -var sprite; - -function create() { - - map = game.add.tilemap('desert'); - - map.addTilesetImage('Desert', 'tiles'); - - layer = map.createLayer('Ground'); - - layer.resizeWorld(); - - sprite = game.add.sprite(450, 80, 'car'); - sprite.anchor.setTo(0.5, 0.5); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.addOnce(swapTiles, this); - -} - -function swapTiles() { - - // This will swap every instance of tile 30 (empty ground) with tile 31 (the cactus plant), it also does the opposite, - // so tile 31 (cactus plants) will become empty ground (tile 30). It does this across the whole layer of the map. - - // You can also pass in x, y, width, height values to control the area in which the swap happens - - map.swap(30, 31); - -} - -function update() { - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -200; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 200; - } - - if (cursors.up.isDown) - { - sprite.body.velocity.copyFrom(game.physics.velocityFromAngle(sprite.angle, 300)); - } - -} - -function render() { - - game.debug.text('Click to swap tiles', 32, 32, 'rgb(0,0,0)'); - game.debug.text('Tile X: ' + layer.getTileX(sprite.x), 32, 48, 'rgb(0,0,0)'); - game.debug.text('Tile Y: ' + layer.getTileY(sprite.y), 32, 64, 'rgb(0,0,0)'); - -} diff --git a/examples/tilemaps/tile callbacks.js b/examples/tilemaps/tile callbacks.js deleted file mode 100644 index 51e5c38eb..000000000 --- a/examples/tilemaps/tile callbacks.js +++ /dev/null @@ -1,97 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/tile_collision_test.json', null, Phaser.Tilemap.TILED_JSON); - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('phaser', 'assets/sprites/arrow.png'); - game.load.spritesheet('coin', 'assets/sprites/coin.png', 32, 32); - -} - -var map; -var layer; - -var sprite; -var cursors; - -function create() { - - game.physics.startSystem(Phaser.Physics.ARCADE); - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('coin'); - - map.setCollisionBetween(1, 12); - - // This will set Tile ID 26 (the coin) to call the hitCoin function when collided with - map.setTileIndexCallback(26, hitCoin, this); - - // This will set the map location 2, 0 to call the function - map.setTileLocationCallback(2, 0, 1, 1, hitCoin, this); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - sprite = game.add.sprite(260, 100, 'phaser'); - sprite.anchor.set(0.5); - game.physics.enable(sprite); - - sprite.body.setSize(16, 16, 8, 8); - - // We'll set a lower max angular velocity here to keep it from going totally nuts - sprite.body.maxAngular = 500; - - // Apply a drag otherwise the sprite will just spin and never slow down - sprite.body.angularDrag = 50; - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function hitCoin(sprite, tile) { - - tile.alpha = 0.2; - - layer.dirty = true; - - return false; - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -300; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 300; - } - - if (cursors.up.isDown) - { - game.physics.arcade.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - -} - -function render() { - - game.debug.body(sprite); - -} \ No newline at end of file diff --git a/examples/tilemaps/tilemap ray cast.js b/examples/tilemaps/tilemap ray cast.js deleted file mode 100644 index c074a92cb..000000000 --- a/examples/tilemaps/tilemap ray cast.js +++ /dev/null @@ -1,127 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - -} - -var map; -var layer; -var cursors; -var sprite; -var line; -var tileHits = []; -var plotting = false; - -function create() { - - line = new Phaser.Line(); - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - map.setCollisionBetween(1, 12); - - layer.debug = true; - - sprite = game.add.sprite(260, 70, 'phaser'); - - game.physics.enable(sprite); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - var help = game.add.text(10, 10, 'Arrows to move, click and drag to cast a ray', { font: '16px Arial', fill: '#ffffff' }); - help.fixedToCamera = true; - - game.input.onDown.add(startLine, this); - game.input.onUp.add(raycast, this); - -} - -function startLine(pointer) { - - if (tileHits.length > 0) - { - for (var i = 0; i < tileHits.length; i++) - { - tileHits[i].debug = false; - } - - layer.dirty = true; - } - - line.start.set(pointer.worldX, pointer.worldY); - - plotting = true; - -} - -function raycast(pointer) { - - line.end.set(pointer.worldX, pointer.worldY); - - tileHits = layer.getRayCastTiles(line, 4, false, false); - - if (tileHits.length > 0) - { - // Just so we can visually see the tiles - for (var i = 0; i < tileHits.length; i++) - { - tileHits[i].debug = true; - } - - layer.dirty = true; - } - - plotting = false; - -} - -function update() { - - if (plotting) - { - line.end.set(game.input.activePointer.worldX, game.input.activePointer.worldY); - } - - game.physics.arcade.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - } - -} - -function render() { - - game.debug.geom(line); - -} diff --git a/examples/time/basic looped event.js b/examples/time/basic looped event.js deleted file mode 100644 index 446e00d7f..000000000 --- a/examples/time/basic looped event.js +++ /dev/null @@ -1,44 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('ball', 'assets/sprites/pangball.png'); - -} - -var counter = 0; -var text = 0; - -function create() { - - game.stage.backgroundColor = '#6688ee'; - - text = game.add.text(game.world.centerX, game.world.centerY, 'Counter: 0', { font: "64px Arial", fill: "#ffffff", align: "center" }); - text.anchor.setTo(0.5, 0.5); - - // Here we'll create a basic looped event. - // A looped event is like a repeat event but with no limit, it will literally repeat itself forever, or until - - // The first parameter is how long to wait before the event fires. In this case 1 second (you could pass in 1000 as the value as well.) - // The next two parameters are the function to call ('updateCounter') and the context under which that will happen. - - - game.time.events.loop(Phaser.Timer.SECOND, updateCounter, this); - -} - -function updateCounter() { - - counter++; - - text.setText('Counter: ' + counter); - -} - -function render() { - - game.debug.text("Time until event: " + game.time.events.duration.toFixed(0), 32, 32); - game.debug.text("Next tick: " + game.time.events.next.toFixed(0), 32, 64); - -} diff --git a/examples/time/basic repeat event.js b/examples/time/basic repeat event.js deleted file mode 100644 index 9767d2733..000000000 --- a/examples/time/basic repeat event.js +++ /dev/null @@ -1,45 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('ball', 'assets/sprites/pangball.png'); - -} - -function create() { - - game.stage.backgroundColor = '#6688ee'; - - // Here we'll create a basic repeating event. - - // The way a repeating event works is that it is placed into the queue once, - // and when it runs its 'repeatCounter' is reduced by 1 and it's moved back into the queue again. - // To this end the queue will only ever have 1 event actually in it. - - // The first parameter is how long to wait before the event fires. In this case 2 seconds (you could pass in 2000 as the value as well.) - // The second parameter is how many times the event will run in total. Here we'll run it 10 times. - // The next two parameters are the function to call ('createBall') and the context under which that will happen. - - // Once the event has been called 10 times it will never be called again. - - game.time.events.repeat(Phaser.Timer.SECOND * 2, 10, createBall, this); - -} - -function createBall() { - - // A bouncey ball sprite just to visually see what's going on. - - var ball = game.add.sprite(game.world.randomX, 0, 'ball'); - - game.physics.enable(ball, Phaser.Physics.ARCADE); - -} - -function render() { - - game.debug.text("Time until event: " + game.time.events.duration.toFixed(0), 32, 32); - game.debug.text("Next tick: " + game.time.events.next.toFixed(0), 32, 64); - -} diff --git a/examples/time/basic timed event.js b/examples/time/basic timed event.js deleted file mode 100644 index b5956d18b..000000000 --- a/examples/time/basic timed event.js +++ /dev/null @@ -1,37 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('bisley', 'assets/pics/alex-bisleys_horsy_5.png'); - -} - -var picture; - -function create() { - - game.stage.backgroundColor = '#6688ee'; - - picture = game.add.sprite(game.world.centerX, game.world.centerY, 'bisley'); - picture.anchor.setTo(0.5, 0.5); - - // Here we'll create a basic timed event. This is a one-off event, it won't repeat or loop: - // The first parameter is how long to wait before the event fires. In this case 4 seconds (you could pass in 4000 as the value as well.) - // The next parameter is the function to call ('fadePicture') and finally the context under which that will happen. - - game.time.events.add(Phaser.Timer.SECOND * 4, fadePicture, this); - -} - -function fadePicture() { - - game.add.tween(picture).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); - -} - -function render() { - - game.debug.text("Time until event: " + game.time.events.duration, 32, 32); - -} diff --git a/examples/time/remove event.js b/examples/time/remove event.js deleted file mode 100644 index 0e34f1a33..000000000 --- a/examples/time/remove event.js +++ /dev/null @@ -1,55 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, render: render }); - -var counters = []; -var text = []; -var timerEvents = []; -var i = 9; - -function create() { - - game.stage.backgroundColor = '#6688ee'; - - for (var i = 0; i < 10; i++) - { - counters[i] = 0; - text[i] = game.add.text(game.world.centerX, 80 + (40 * i), 'Counter ' + i + ' = 0', { font: "32px Arial", fill: "#ffffff", align: "center" }); - text[i].anchor.setTo(0.5, 0); - - // Here we create our timer events. They will be set to loop at a random value between 250ms and 1000ms - timerEvents[i] = game.time.events.loop(game.rnd.integerInRange(250, 1000), updateCounter, this, i); - } - - // Click to remove - game.input.onDown.add(removeCounter, this); - -} - -function updateCounter(idx) { - - counters[idx]++; - - text[idx].setText('Counter ' + idx + ' = ' + counters[idx]); - -} - -function removeCounter() { - - if (i >= 0) - { - // Removes the timer, starting with the top one and working down - game.time.events.remove(timerEvents[i]); - - // Just updates the text - text[i].style.fill = '#3344aa'; - text[i].setText('Counter ' + i + ' removed'); - i--; - } - -} - -function render() { - - game.debug.text("Queued events: " + game.time.events.length + ' - click to remove', 32, 32); - -} diff --git a/examples/time/timed slideshow.js b/examples/time/timed slideshow.js deleted file mode 100644 index 26cc2edb5..000000000 --- a/examples/time/timed slideshow.js +++ /dev/null @@ -1,94 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('picture1', 'assets/pics/cougar_sanity_train.png'); - game.load.image('picture2', 'assets/pics/cougar-face_of_nature.png'); - game.load.image('picture3', 'assets/pics/destop-rewarding.png'); - game.load.image('picture4', 'assets/pics/destop-unknown.png'); - game.load.image('picture5', 'assets/pics/questar.png'); - game.load.image('picture6', 'assets/pics/seven_seas_andromeda_fairfax.png'); - game.load.image('picture7', 'assets/pics/slayer-sorry_im_the_beast.png'); - -} - -var pictureA; -var pictureB; -var timer; -var current = 3; - -function create() { - - game.stage.backgroundColor = '#000'; - - pictureA = game.add.sprite(game.world.centerX, game.world.centerY, 'picture1'); - pictureA.anchor.setTo(0.5, 0.5); - pictureA.scale.setTo(2, 2); - - pictureB = game.add.sprite(game.world.centerX, game.world.centerY, 'picture2'); - pictureB.anchor.setTo(0.5, 0.5); - pictureB.scale.setTo(2, 2); - pictureB.alpha = 0; - - // Create our Timer - timer = game.time.create(false); - - // Set a TimerEvent to occur after 3 seconds - timer.add(3000, fadePictures, this); - - // Start the timer running - this is important! - // It won't start automatically, allowing you to hook it to button events and the like. - timer.start(); - -} - -function fadePictures() { - - // Cross-fade the two pictures - var tween; - - if (pictureA.alpha === 1) - { - tween = game.add.tween(pictureA).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); - game.add.tween(pictureB).to( { alpha: 1 }, 2000, Phaser.Easing.Linear.None, true); - } - else - { - game.add.tween(pictureA).to( { alpha: 1 }, 2000, Phaser.Easing.Linear.None, true); - tween = game.add.tween(pictureB).to( { alpha: 0 }, 2000, Phaser.Easing.Linear.None, true); - } - - // When the cross-fade is complete we swap the image being shown by the now hidden picture - tween.onComplete.add(changePicture, this); - -} - -function changePicture() { - - if (pictureA.alpha === 0) - { - pictureA.loadTexture('picture' + current); - } - else - { - pictureB.loadTexture('picture' + current); - } - - current++; - - if (current > 7) - { - current = 1; - } - - // And set a new TimerEvent to occur after 3 seconds - timer.add(3000, fadePictures, this); - -} - -function render() { - - game.debug.text("Time until event: " + timer.duration.toFixed(0), 10, 20); - -} diff --git a/examples/tweens/bounce.js b/examples/tweens/bounce.js deleted file mode 100644 index cbb7185e4..000000000 --- a/examples/tweens/bounce.js +++ /dev/null @@ -1,29 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('ball', 'assets/sprites/yellow_ball.png'); - -} - -var ball; - -function create() { - - ball = game.add.sprite(300, 0, 'ball'); - - startBounceTween(); -} - -function startBounceTween() { - - ball.y = 0; - - var bounce=game.add.tween(ball); - - bounce.to({ y: game.world.height-ball.height }, 1000 + Math.random() * 3000, Phaser.Easing.Bounce.In); - bounce.onComplete.add(startBounceTween, this); - bounce.start(); - -} diff --git a/examples/tweens/bubbles.js b/examples/tweens/bubbles.js deleted file mode 100644 index e71f967da..000000000 --- a/examples/tweens/bubbles.js +++ /dev/null @@ -1,26 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('space', 'assets/misc/starfield.png', 138, 15); - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -function create() { - - game.add.tileSprite(0, 0, 800, 600, 'space'); - - for (var i = 0; i < 30; i++) - { - var sprite = game.add.sprite(game.world.randomX,game.world.randomY,'ball'); - - // Fade in a sprite - game.add.tween(sprite).to({ y: -50 }, Math.random() * 4500, Phaser.Easing.Cubic.Out, true); - - // This tween starts with a random length delay - game.add.tween(sprite).to({ alpha: 0 }, Math.random() * 4500, Phaser.Easing.Quadratic.InOut, true, Math.random() * 500); - } - -} diff --git a/examples/tweens/chained tweens.js b/examples/tweens/chained tweens.js deleted file mode 100644 index e324d0438..000000000 --- a/examples/tweens/chained tweens.js +++ /dev/null @@ -1,24 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('diamond', 'assets/sprites/diamond.png'); - -} - -function create() { - - game.stage.backgroundColor = 0x2d2d2d; - - var sprite = game.add.sprite(100, 100, 'diamond'); - - // Here we'll chain 4 different tweens together and play through them all in a loop - var tween = game.add.tween(sprite).to({ x: 600 }, 2000, Phaser.Easing.Linear.None) - .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) - .to({ x: 100 }, 2000, Phaser.Easing.Linear.None) - .to({ y: 100 }, 1000, Phaser.Easing.Linear.None) - .loop() - .start(); - -} diff --git a/examples/tweens/combined tweens.js b/examples/tweens/combined tweens.js deleted file mode 100644 index b228b1c9e..000000000 --- a/examples/tweens/combined tweens.js +++ /dev/null @@ -1,52 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', {preload:preload,create: create }); - -function preload() { - - game.load.spritesheet('pig', 'assets/sprites/invaderpig.png', 124, 104); - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -var mushroom; -var pig; -var pigArrives; -var s; - -function create() { - - game.add.tileSprite(0, 0, 800, 600, 'starfield'); - - pig = game.add.sprite(-50, 200, 'pig', 1); - - pig.scale.setTo(0.5, 0.5); - - mushroom = game.add.sprite(380, 200, 'mushroom'); - mushroom.anchor.setTo(0.5, 0.5); - - pigArrives = game.add.tween(pig); - - pigArrives.to({x:150}, 1000, Phaser.Easing.Bounce.Out); - pigArrives.onComplete.add(firstTween, this); - pigArrives.start(); - -} - -function firstTween() { - - s = game.add.tween(mushroom.scale); - s.to({x: 2, y:2}, 1000, Phaser.Easing.Linear.None); - s.onComplete.addOnce(theEnd, this); - s.start(); - -} - -function theEnd() { - - e = game.add.tween(pig); - - e.to({ x: -150 }, 1000, Phaser.Easing.Bounce.Out); - e.start(); - -} diff --git a/examples/tweens/easing spritesheets.js b/examples/tweens/easing spritesheets.js deleted file mode 100644 index 02d93b803..000000000 --- a/examples/tweens/easing spritesheets.js +++ /dev/null @@ -1,25 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', {preload:preload,create: create }); - -function preload() { - - game.load.spritesheet('phaser', 'assets/tests/tween/phaser.png', 70, 90); - game.load.image('starfield', 'assets/misc/starfield.jpg'); - -} - -function create() { - - var item; - - game.add.tileSprite(0, 0, 800, 600, 'starfield'); - - for (var i = 0; i < 6; i++) - { - item = game.add.sprite(190 + 69 * i, -90, 'phaser', i); - - // Add a simple bounce tween to each character's position. - game.add.tween(item).to({y: 240}, 2400, Phaser.Easing.Bounce.Out, true, 1000 + 400 * i, false); - } - -} diff --git a/examples/tweens/easing.js b/examples/tweens/easing.js deleted file mode 100644 index 5be7e59a7..000000000 --- a/examples/tweens/easing.js +++ /dev/null @@ -1,46 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.spritesheet('shadow', 'assets/tests/tween/shadow.png', 138, 15); - game.load.spritesheet('phaser', 'assets/tests/tween/phaser.png', 70, 90); - -} - -function create() { - - var item; - var shadow; - var tween; - - // Sets background color to white. - game.stage.backgroundColor = '#ffffff'; - - for (var i = 0; i < 6; i++) - { - // Add a shadow to the location which characters will land on. - // And tween their size to make them look like a real shadow. - // Put the following code before items to give shadow a lower - // render order. - shadow = game.add.sprite(190 + 69 * i, 284, 'shadow'); - - // Set shadow's size 0 so that it'll be invisible at the beginning. - shadow.scale.setTo(0.0, 0.0); - - // Also set the origin to the center since we don't want to - // see the shadow scale to the left top. - shadow.anchor.setTo(0.5, 0.5); - game.add.tween(shadow.scale).to({x: 1.0, y: 1.0}, 2400, Phaser.Easing.Bounce.Out, true); - - // Add characters on top of shadows. - item = game.add.sprite(190 + 69 * i, -50, 'phaser', i); - - // Set origin to the center to make the rotation look better. - item.anchor.setTo(0.5, 0.5); - - // Add a simple bounce tween to each character's position. - tween = game.add.tween(item).to( { y: 245 }, 2400, Phaser.Easing.Bounce.Out, true); - } - -} diff --git a/examples/tweens/fading in a sprite.js b/examples/tweens/fading in a sprite.js deleted file mode 100644 index 5b43a76ef..000000000 --- a/examples/tweens/fading in a sprite.js +++ /dev/null @@ -1,22 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('space', 'assets/misc/starfield.png', 138, 15); - game.load.image('logo', 'assets/sprites/phaser2.png'); - -} - -function create() { - - game.add.tileSprite(0, 0, 800, 600, 'space'); - - var sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'logo'); - - sprite.anchor.setTo(0.5, 0.5); - sprite.alpha = 0; - - game.add.tween(sprite).to( { alpha: 1 }, 2000, Phaser.Easing.Linear.None, true, 0, 1000, true); - -} diff --git a/examples/tweens/generate data.js b/examples/tweens/generate data.js deleted file mode 100644 index 8d5c010c2..000000000 --- a/examples/tweens/generate data.js +++ /dev/null @@ -1,88 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('wasp', 'assets/sprites/wasp.png'); - game.load.image('sky', 'assets/skies/cavern1.png'); - -} - -var bugs; -var index = 0; -var data; -var pos = []; - -function create() { - - game.add.image(0, 0, 'sky'); - - // image = game.add.image(0, 0, 'wasp'); - - // We don't want it to actually run, so we use game.make.tween instead of game.add.tween - - var tweenData = { x: 0, y: 0 }; - - // Here we'll tween the values held in the tweenData object to x: 500, y: 300 - tween = game.make.tween(tweenData).to( { x: 100, y: 400 }, 2000, Phaser.Easing.Sinusoidal.InOut); - - // Set the tween to yoyo so it loops smoothly - tween.yoyo(true); - - // We have 3 interpolation methods available: linearInterpolation (the default), bezierInterpolation and catmullRomInterpolation. - - // tween.interpolation(game.math.bezierInterpolation); - tween.interpolation(game.math.catmullRomInterpolation); - - // Generates the tween data at a rate of 60 frames per second. - // This is useful if you've got a lot of objects all using the same tween, just at different coordinates. - // It saves having to calculate the same tween across the properties of all objects involved in the motion. - // Instead you can pre-calculate it in advance and trade that in for a bit of memory to store it in an array. - data = tween.generateData(60); - - // Now create some sprites to shown the tween data in action - bugs = game.add.group(); - - pos.push(new Phaser.Point(32, 0)); - pos.push(new Phaser.Point(300, 100)); - pos.push(new Phaser.Point(600, 70)); - - bugs.create(pos[0].x, pos[0].y, 'wasp'); - bugs.create(pos[1].x, pos[1].y, 'wasp'); - bugs.create(pos[2].x, pos[2].y, 'wasp'); - -} - -function update() { - - // A simple data playback. - - // Each element of the array contains an object that includes whatever properties were tweened - // In this case the x and y properties - - // Because the tween data is pre-generated we can apply it however we want: - // Directly, by adding to the coordinates - bugs.getAt(0).x = pos[0].x + data[index].x; - bugs.getAt(0).y = pos[0].y + data[index].y; - - // Half one of the values - bugs.getAt(1).x = pos[1].x + (data[index].x / 2); - bugs.getAt(1).y = pos[1].y + data[index].y; - - // Inverse one of the values - bugs.getAt(2).x = pos[2].x - data[index].x; - bugs.getAt(2).y = pos[2].y + data[index].y; - - // You can do all kinds of effects by modifying the tween data, - // without having loads of active tweens running. - - // This just advances the tween data index - // It's crude and doesn't take target device speed into account at all, but works as an example - index++; - - if (index === data.length) - { - index = 0; - } - -} diff --git a/examples/tweens/pause tween.js b/examples/tweens/pause tween.js deleted file mode 100644 index c6689e959..000000000 --- a/examples/tweens/pause tween.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -var p; -var tween; -var button; -var flag = true; - -function preload() { - - game.load.image('diamond', 'assets/sprites/diamond.png'); - game.load.spritesheet('button', 'assets/buttons/button_sprite_sheet.png', 193, 71); - -} - -function create() { - - game.stage.backgroundColor = 0x2d2d2d; - - p = game.add.sprite(100, 100, 'diamond'); - - tween = game.add.tween(p).to({ x: 600 }, 4000, Phaser.Easing.Linear.None, true, 0, 1000, true) - - button = game.add.button(game.world.centerX, 400, 'button', actionOnClick, this, 2, 1, 0); - -} - -function actionOnClick() { - - if (flag) - { - tween.pause(); - } - else - { - tween.resume(); - } - - flag = !flag; - -} diff --git a/examples/tweens/tween loop event.js b/examples/tweens/tween loop event.js deleted file mode 100644 index 19545584b..000000000 --- a/examples/tweens/tween loop event.js +++ /dev/null @@ -1,63 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.spritesheet('balls', 'assets/sprites/balls.png', 17, 17); - -} - -var ball; -var tween; -var bounces = 10; - -function create() { - - ball = game.add.sprite(400, 0, 'balls', 0); - - tween = game.add.tween(ball).to( { y: game.world.height - ball.height }, 1500, Phaser.Easing.Bounce.Out, true, 2500, 10); - - // There is a 2.5 second delay at the start, then it calls this function - tween.onStart.add(onStart, this); - - // This tween will loop 10 times, calling this function every time it loops - tween.onLoop.add(onLoop, this); - - // When it completes it will call this function - tween.onComplete.add(onComplete, this); - -} - -function onStart() { - - // Turn off the delay, so it loops seamlessly from here on - tween.delay(0); - -} - -function onLoop() { - - bounces--; - - if (ball.frame === 5) - { - ball.frame = 0; - } - else - { - ball.frame++; - } - -} - -function onComplete() { - - tween = game.add.tween(ball).to( { x: 800 - ball.width }, 2000, Phaser.Easing.Exponential.Out, true); - -} - -function render() { - - game.debug.text('Bounces: ' + bounces, 32, 32); - -} \ No newline at end of file diff --git a/examples/tweens/tween relative.js b/examples/tweens/tween relative.js deleted file mode 100644 index 0f36d16a1..000000000 --- a/examples/tweens/tween relative.js +++ /dev/null @@ -1,57 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser1.png'); - game.load.spritesheet('arrows', 'assets/sprites/arrows.png', 23, 31); - -} - -var arrowStart; -var arrowEnd; -var sprite; - -function create() { - - game.stage.backgroundColor = '#2384e7'; - - arrowStart = game.add.sprite(100, 100, 'arrows', 0); - - arrowEnd = game.add.sprite(400, 100, 'arrows', 1); - - sprite = game.add.sprite(100, 164, 'phaser'); - sprite.inputEnabled = true; - - sprite.events.onInputDown.add(move, this); - -} - -function move() { - - if (sprite.x === 100) - { - // Here you'll notice we are using a relative value for the tween. - // You can specify a number as a string with either + or - at the start of it. - // When the tween starts it will take the sprites current X value and add +300 to it. - - game.add.tween(sprite).to( { x: '+300' }, 2000, Phaser.Easing.Linear.None, true); - } - else if (sprite.x === 400) - { - game.add.tween(sprite).to( { x: '-300' }, 2000, Phaser.Easing.Linear.None, true); - } - -} - -function render() { - - if (sprite.x === 100 || sprite.x === 400) - { - game.debug.text('Click sprite to tween', 32, 32); - } - - game.debug.text('x: ' + arrowStart.x, arrowStart.x, arrowStart.y - 4); - game.debug.text('x: ' + arrowEnd.x, arrowEnd.x, arrowEnd.y - 4); - -} diff --git a/examples/tweens/tween several properties.js b/examples/tweens/tween several properties.js deleted file mode 100644 index ff72610e2..000000000 --- a/examples/tweens/tween several properties.js +++ /dev/null @@ -1,29 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('sky', 'assets/skies/sky4.png'); - game.load.spritesheet('phaser', 'assets/tests/tween/phaser.png', 70, 90); - -} - -function create() { - - game.add.sprite(0, 0, 'sky'); - - var item; - - for (var i = 0; i < 6; i++) - { - item = game.add.sprite(190 + 69 * i, -100, 'phaser', i); - item.anchor.setTo(0.5,0.5); - - // Add a simple bounce tween to each character's position. - game.add.tween(item).to({y: 240}, 2400, Phaser.Easing.Bounce.Out, true, 1000 + 400 * i, false); - - // Add another rotation tween to the same character. - game.add.tween(item).to({angle: 360}, 2400, Phaser.Easing.Cubic.In, true, 1000 + 400 * i, false); - } - -} diff --git a/examples/where have they gone.txt b/examples/where have they gone.txt new file mode 100644 index 000000000..fa49944f3 --- /dev/null +++ b/examples/where have they gone.txt @@ -0,0 +1,6 @@ +Ever since we started Phaser we've been growing and expanding our extensive set of Examples. + +They used to be bundled in the main Phaser repo, but because they got so large and in order +to help with versioning we've moved them to their own repository: + +https://github.com/photonstorm/phaser-examples diff --git a/examples/wip/TweenGroup.js b/examples/wip/TweenGroup.js deleted file mode 100644 index e2ad740c3..000000000 --- a/examples/wip/TweenGroup.js +++ /dev/null @@ -1,482 +0,0 @@ -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* TweenGroup constructor -* Create a new TweenGroup. -* -* @class Phaser.TweenGroup -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {number} delay - Delay before this tween will start, defaults to 0 (no delay). -* @param {number} repeat - How many time should the TweenGroup repeat itself. Infinity can be used for infinite repetition. -* @param {Phaser.Tween} yoyo - Whether this TweenGroup will reverse on completion. -* @param {boolean} autoStart - Whether this TweenGroup will start automatically or not. -*/ -Phaser.TweenGroup = function (game, delay, repeat, yoyo, autoStart) { - - autoStart = autoStart || true; - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {number} _duration - Description. - * @private - * @default - */ - this._duration = 0; - - /** - * @property {number} _repeat - Description. - * @private - * @default - */ - this._repeat = repeat || 0; - - /** - * @property {boolean} _yoyo - Description. - * @private - * @default - */ - this._yoyo = yoyo || false; - - /** - * @property {boolean} _reversed - Description. - * @private - * @default - */ - this._reversed = false; - - /** - * @property {number} _delayTime - Description. - * @private - * @default - */ - this._delayTime = delay || 0; - - /** - * @property {Description} _startTime - Description. - * @private - * @default null - */ - this._startTime = null; - - /** - * @property {Description} _onStartCallback - Description. - * @private - * @default - */ - this._onStartCallback = null; - - /** - * @property {boolean} _onStartCallbackFired - Description. - * @private - * @default - */ - this._onStartCallbackFired = false; - - /** - * @property {Description} _onUpdateCallback - Description. - * @private - * @default null - */ - this._onUpdateCallback = null; - - /** - * @property {Description} _onCompleteCallback - Description. - * @private - * @default null - */ - this._onCompleteCallback = null; - - /** - * @property {boolean} _paused - Description. - * @private - * @default false - */ - this._paused = false; - - /** - * @property {number} _pausedTime - Description. - * @private - * @default - */ - this._pausedTime = 0; - - /** - * @property {boolean} pendingDelete - If this TweenGroup is ready to be deleted by the TweenManager. - * @default - */ - this.pendingDelete = false; - - /** - * @property {Phaser.Signal} onStart - Description. - */ - this.onStart = new Phaser.Signal(); - - /** - * @property {Phaser.Signal} onComplete - Description. - */ - this.onComplete = new Phaser.Signal(); - - /** - * @property {boolean} isRunning - Description. - * @default - */ - this.isRunning = false; - - /** - * @property {number} _time - Description. - * @private - */ - this._time = 0; - - /** - * @property {array} _tweens - Description. - * @private - */ - this._tweens = []; - - /** - * @property {array} _add - Description. - * @private - */ - this._add = []; - - /** - * @property {boolean} _dirty - Description. - * @private - */ - this._dirty = false; - - if (autoStart) { - this.start(); - } - -}; - -Phaser.TweenGroup.prototype = { - - /** - * Create and configure a tween that will be added to this group - * - * @method Phaser.TweenGroup#to - * @param {object} object - Object to tween. - * @param {object} properties - Properties you want to tween. - * @param {number} duration - Duration of this tween. - * @param {function} ease - Easing function. - * @param {boolean} autoStart - Whether this tween will start automatically or not. - * @param {number} delay - Delay before this tween will start, defaults to 0 (no delay). - * @param {boolean} repeat - Should the tween automatically restart once complete? (ignores any chained tweens). - * @param {Phaser.Tween} yoyo - Description. - * @return {Phaser.TweenGroup} Itself. - */ - to: function ( object, properties, duration, ease, autoStart, delay, repeat, yoyo ) { - - var tween = new Phaser.Tween(object, this.game); - tween.to(properties, duration, ease, autoStart, delay, repeat, yoyo); - this.add(tween); - - return this; - - }, - - /** - * Starts the TweenGroup. - * - * @method Phaser.TweenGroup#start - * @return {Phaser.TweenGroup} Itself. - */ - start: function () { - - this.game.tweens.add(this); - - this.onStart.dispatch(); - - this.isRunning = true; - - this._onStartCallbackFired = false; - - this._startTime = this.game.time.now + this._delayTime; - - return this; - - }, - - /** - * Stops the TweenGroup if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched. - * - * @method Phaser.TweenGroup#stop - * @return {Phaser.TweenGroup} Itself. - */ - stop: function () { - - this.game.tweens.remove(this); - this.isRunning = false; - - return this; - - }, - - /** - * Sets a delay time before this tween will start. - * - * @method Phaser.TweenGroup#delay - * @param {number} amount - The amount of the delay in ms. - * @return {Phaser.TweenGroup} Itself. - */ - delay: function ( amount ) { - - this._delayTime = amount; - return this; - - }, - - /** - * Sets the number of times this tween will repeat. - * - * @method Phaser.TweenGroup#repeat - * @param {number} times - How many times to repeat. - * @return {Phaser.TweenGroup} Itself. - */ - repeat: function ( times ) { - - this._repeat = times; - return this; - - }, - - /** - * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start. - * Used in combination with repeat you can create endless loops. - * - * @method Phaser.TweenGroup#yoyo - * @param {boolean} yoyo - Set to true to yoyo this tween. - * @return {Phaser.TweenGroup} Itself. - */ - yoyo: function( yoyo ) { - - this._yoyo = yoyo; - return this; - - }, - - /** - * Sets a callback to be fired when the tween starts. Note: callback will be called in the context of the global scope. - * - * @method Phaser.TweenGroup#onStartCallback - * @param {function} callback - The callback to invoke on start. - * @return {Phaser.TweenGroup} Itself. - */ - onStartCallback: function ( callback ) { - - this._onStartCallback = callback; - return this; - - }, - - /** - * Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope. - * - * @method Phaser.TweenGroup#onUpdateCallback - * @param {function} callback - The callback to invoke each time this tween is updated. - * @return {Phaser.TweenGroup} Itself. - */ - onUpdateCallback: function ( callback ) { - - this._onUpdateCallback = callback; - return this; - - }, - - /** - * Sets a callback to be fired when the tween completes. Note: callback will be called in the context of the global scope. - * - * @method Phaser.TweenGroup#onCompleteCallback - * @param {function} callback - The callback to invoke on completion. - * @return {Phaser.TweenGroup} Itself. - */ - onCompleteCallback: function ( callback ) { - - this._onCompleteCallback = callback; - return this; - - }, - - /** - * Pauses the tween. - * - * @method Phaser.TweenGroup#pause - */ - pause: function () { - this._paused = true; - this._pausedTime = this.game.time.now; - }, - - /** - * Resumes a paused tween. - * - * @method Phaser.TweenGroup#resume - */ - resume: function () { - this._paused = false; - this._startTime += (this.game.time.now - this._pausedTime); - }, - - /** - * Core tween update function called by the TweenManager. Does not need to be invoked directly. - * - * @method Phaser.TweenGroup#update - * @param {number} time - A timestamp passed in by the TweenManager. - * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active). - */ - update: function ( time ) { - var i = 0, - numTweens = this._tweens.length, - tween = null; - - var rtime = 0; - - if ( this._onStartCallbackFired === false ) { - - if ( this._onStartCallback !== null ) { - - this._onStartCallback.call(this); - - } - - this.onStart.dispatch(this); - - this._onStartCallbackFired = true; - - } - - if ( this._dirty && numTweens > 0) { - - var max = 0; - - for (var j = numTweens - 1; j >= 0; j--) { - tween = this._tweens[j]; - - if ( max < ( tween._startTime + tween._duration ) ) { - max = tween._startTime + tween._duration; - } - } - - this._duration = max; - - this._dirty = false; - - } - - while ( i < numTweens ) { - - tween = this._tweens[ i ]; - - if ( ( time < tween._startTime ) || ( time > ( tween._startTime + tween._duration )) || tween._paused) { - - i++; - continue; - - } - - rtime = time - tween._startTime; - - tween.update( rtime ); - - i++; - } - - if ( this._onUpdateCallback !== null ) { - - this._onUpdateCallback.call(this); - - } - - if ( ( ( time >= this._duration ) && !this._reversed ) || ( ( time <= 0) && this._reversed ) ) { - - this.onComplete.dispatch(this); - - if ( this._onCompleteCallback !== null ) { - this._onCompleteCallback.call(this); - } - - if ( this._repeat > 0 ) { - - if ( isFinite( this._repeat ) ) { - this._repeat--; - } - - if (this._yoyo) { - this._reversed = !this._reversed; - } - - this._startTime = this.game.time.now + this._delayTime; - - } else { - return false; - } - - } - - if (this._add.length > 0) - { - this._tweens = this._tweens.concat(this._add); - this._add.length = 0; - } - - return true; - }, - - /** - * Add a new tween into the TweenGroup. - * - * @method Phaser.TweenGroup#add - * @param {Phaser.Tween} tween - The tween object you want to add. - * @returns {Phaser.Tween} The tween object you added to the group. - */ - add: function ( tween ) { - - if ( this.isRunning ) { - this._add.push( tween ); - } else { - this._tweens.push( tween ); - } - - tween._startTime = this._duration + tween._delayTime; - - if ( ( tween._startTime + tween._duration ) > this._duration ) { - this._duration = tween._startTime + tween._duration; - } - - this._dirty = true; - - }, - - /** - * Remove a tween from this TweenGroup. - * - * @method Phaser.TweenGroup#remove - * @param {Phaser.Tween} tween - The tween object you want to remove. - */ - remove: function ( tween ) { - - var i = this._tweens.indexOf( tween ); - - if ( i !== -1 ) { - - this._tweens[i].pendingDelete = true; - - } - - this._dirty = true; - - } - -}; diff --git a/examples/wip/alpha-mask.js b/examples/wip/alpha-mask.js deleted file mode 100644 index 72d6824fd..000000000 --- a/examples/wip/alpha-mask.js +++ /dev/null @@ -1,34 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', 'assets/pics/questar.png'); - game.load.image('mask1', 'assets/pics/mask-test.png'); - game.load.image('mask2', 'assets/pics/mask-test2.png'); - -} - -var pic; - -function create() { - - var bmd = game.make.bitmapData(320, 256); - - bmd.alphaMask('pic', 'mask2'); - - pic = game.add.sprite(0, 0, bmd); - - pic.scale.set(2); - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/anim-speed.js b/examples/wip/anim-speed.js deleted file mode 100644 index a6fd855e5..000000000 --- a/examples/wip/anim-speed.js +++ /dev/null @@ -1,48 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; -var anim; - -function create() { - - game.stage.backgroundColor = 0x2d2d2d; - - mummy = game.add.sprite(300, 200, 'mummy', 5); - - anim = mummy.animations.add('walk'); - - anim.play(10, true); - - game.input.onDown.add(changeSpeed, this); - -} - -function changeSpeed(pointer) { - - if (pointer.x < 400) - { - anim.speed -= 1; - } - else - { - anim.speed += 1; - } - -} - -function update() { - -} - -function render() { - - game.debug.text(anim.speed, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/anim1.js b/examples/wip/anim1.js deleted file mode 100644 index a6e42d6df..000000000 --- a/examples/wip/anim1.js +++ /dev/null @@ -1,36 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; -var anim; - -function create() { - - game.stage.backgroundColor = 0xff8855; - - mummy = game.add.sprite(300, 200, 'mummy', 5); - - mummy.animations.updateIfVisible = false; - - anim = mummy.animations.add('walk'); - - anim.play(2, false); - // anim.play(2, true); - -} - -function update() { - -} - -function render() { - - game.debug.text(anim.frame + ' / 17', 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/animated tilesprite.js b/examples/wip/animated tilesprite.js deleted file mode 100644 index 1b22906b3..000000000 --- a/examples/wip/animated tilesprite.js +++ /dev/null @@ -1,75 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -var tilesprite; -var cursors; -var count = 0; - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var sprite; - -function create() { - - // sprite = game.add.tileSprite(0, 0, 800, 600, 'starfield'); - // sprite = game.add.tileSprite(100, 100, 400, 300, 'starfield'); - - - // sprite = game.add.tileSprite(0, 0, 800, 600, 'mummy', 0); - // sprite.animations.add('walk'); - // sprite.animations.play('walk', 20, true); - - // x = game.add.sprite(0, 0, 'mummy'); - // x.animations.add('walk'); - // x.animations.play('walk', 20, true); - - sprite = game.add.tileSprite(0, 0, 800, 600, 'seacreatures', 'octopus0000'); - sprite.animations.add('swim', Phaser.Animation.generateFrameNames('octopus', 0, 24, '', 4), 30, true); - sprite.animations.play('swim'); - - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - count += 0.005 - - sprite.tileScale.x = 2 + Math.sin(count); - sprite.tileScale.y = 2 + Math.cos(count); - - sprite.tilePosition.x += 1; - sprite.tilePosition.y += 1; - - if (cursors.left.isDown) - { - sprite.tilePosition.x += 4; - } - else if (cursors.right.isDown) - { - sprite.tilePosition.x -= 4; - } - - if (cursors.up.isDown) - { - sprite.tilePosition.y += 4; - } - else if (cursors.down.isDown) - { - sprite.tilePosition.y -= 4; - } - -} - -function render() { - - // game.debug.text(sprite.frame, 32, 32); - -} diff --git a/examples/wip/animation events.js b/examples/wip/animation events.js deleted file mode 100644 index 1d04dbfba..000000000 --- a/examples/wip/animation events.js +++ /dev/null @@ -1,69 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('lazur', 'assets/pics/thorn_lazur.png'); - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var back; -var mummy; -var anim; -var loopText; - -function create() { - - game.stage.smoothed = false; - - back = game.add.image(0, -400, 'lazur'); - back.scale.set(2); - - mummy = game.add.sprite(200, 360, 'mummy', 5); - mummy.scale.set(4); - - anim = mummy.animations.add('walk'); - - anim.onStart.add(animationStarted, this); - anim.onLoop.add(animationLooped, this); - anim.onComplete.add(animationStopped, this); - - anim.play(10, true); - -} - -function animationStarted(sprite, animation) { - - game.add.text(32, 32, 'Animation started', { fill: 'white' }); - -} - -function animationLooped(sprite, animation) { - - if (animation.loopCount === 1) - { - loopText = game.add.text(32, 64, 'Animation looped', { fill: 'white' }); - } - else - { - loopText.text = 'Animation looped x2'; - animation.loop = false; - } - -} - -function animationStopped(sprite, animation) { - - game.add.text(32, 64+32, 'Animation stopped', { fill: 'white' }); - -} - -function update() { - - if (anim.isPlaying) - { - back.x -= 1; - } - -} \ No newline at end of file diff --git a/examples/wip/astro balls.js b/examples/wip/astro balls.js deleted file mode 100644 index d1b1901bd..000000000 --- a/examples/wip/astro balls.js +++ /dev/null @@ -1,103 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('arrow', 'assets/sprites/arrow.png'); - game.load.image('arrow', 'assets/sprites/thrust_ship2.png'); - game.load.image('chunk', 'assets/sprites/chunk.png'); - game.load.spritesheet('bullets', 'assets/sprites/balls.png', 17, 17); - -} - -var cannon; -var bullets; -var angle = 0; -var fireRate = 100; -var nextFire = 0; -var cursors; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - game.physics.gravity[1] = -8.5; - game.physics.defaultRestitution = 0.8; - game.physics.defaultFriction = 0.1; - - bullets = game.add.group(); - bullets.createMultiple(250, 'bullets', 0, false); - - cannon = game.add.sprite(50, 500, 'arrow'); - cannon.physicsEnabled = true; - cannon.body.kinematic = true; - cannon.body.mass = 4; - cursors = game.input.keyboard.createCursorKeys(); - -} - -function fire() { - - if (game.time.now > nextFire) - { - nextFire = game.time.now + fireRate; - - var bullet = bullets.getFirstExists(false); - - if (bullet) - { - bullet.frame = game.rnd.integerInRange(0,6); - bullet.exists = true; - bullet.position.set(cannon.x, cannon.y); - bullet.physicsEnabled = true; - - bullet.body.rotation = cannon.rotation + game.math.degToRad(90); - - var magnitude = game.math.px2p(-500); - var angle = bullet.body.rotation + Math.PI / 2; - - bullet.body.velocity.x = magnitude * Math.cos(angle); - bullet.body.velocity.y = magnitude * Math.sin(angle); - } - } - -} - -function update() { - - if (cursors.left.isDown) - { - cannon.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - cannon.body.rotateRight(100); - } - else - { - cannon.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - cannon.body.moveForward(200); - } - else if (cursors.down.isDown) - { - cannon.body.moveBackward(200); - } - - var dx = game.input.activePointer.worldX - cannon.x; - var dy = game.input.activePointer.worldY - cannon.y; - cannon.rotation = Math.atan2(dy, dx); - - if (game.input.activePointer.isDown) - { - fire(); - } - -} - -function render() { - -} diff --git a/examples/wip/atari balls.js b/examples/wip/atari balls.js deleted file mode 100644 index ea66d7d15..000000000 --- a/examples/wip/atari balls.js +++ /dev/null @@ -1,99 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - game.load.spritesheet('bullets', 'assets/sprites/balls.png', 17, 17); - -} - -var atari; -var balls; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - balls = game.add.group(); - - balls.createMultiple(250, 'bullets', 0, false); - - atari = game.add.sprite(300, 450, 'atari'); - - game.physics.arcade.gravity.y = 400; - - // Enable physics on everything added to the world so far (the true parameter makes it recurse down into children) - game.physics.arcade.enable(game.world, true); - - atari.body.gravityScale.y = 0; - atari.body.immovable = true; - - cursors = game.input.keyboard.createCursorKeys(); - - game.time.events.loop(150, fire, this); - -} - -function fire() { - - var ball = balls.getFirstExists(false); - - if (ball) - { - ball.frame = game.rnd.integerInRange(0,6); - ball.exists = true; - ball.reset(game.world.randomX, 0); - - ball.body.bounce.y = 0.8; - } - -} - -function reflect(a, ball) { - - if (ball.y > (atari.y + 5)) - { - return true; - } - else - { - ball.body.velocity.x = atari.body.velocity.x; - ball.body.velocity.y *= -(ball.body.bounce.y); - - return false; - } - -} - -function update() { - - game.physics.arcade.collide(atari, balls, null, reflect, this); - - atari.body.velocity.x = 0; - - if (cursors.left.isDown) - { - atari.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - atari.body.velocity.x = 200; - } - - balls.forEachAlive(checkBounds, this); - -} - -function checkBounds(ball) { - - if (ball.y > 600) - { - ball.kill(); - } - -} - -function render() { - -} diff --git a/examples/wip/atlas_trim_array.js b/examples/wip/atlas_trim_array.js deleted file mode 100644 index a3c09512d..000000000 --- a/examples/wip/atlas_trim_array.js +++ /dev/null @@ -1,24 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - // Non-trimmed - // game.load.atlasJSONArray('atlas', 'assets/sprites/atlas_array_no_trim.png', 'assets/sprites/atlas_json_array_no_trim.json'); - // game.load.atlasJSONHash('atlas', 'assets/sprites/atlas_hash_no_trim.png', 'assets/sprites/atlas_json_hash_no_trim.json'); - - // Trimmed - // game.load.atlasJSONArray('atlas', 'assets/sprites/atlas_array_trim.png', 'assets/sprites/atlas_json_array_trim.json'); - game.load.atlasJSONHash('atlas', 'assets/sprites/atlas_hash_trim.png', 'assets/sprites/atlas_json_hash_trim.json'); - -} - -var sprite; - -function create() { - - sprite = game.add.sprite(330, 100, 'atlas', 'nanoha_taiken_blue'); - - sprite = game.add.sprite(530, 100, 'atlas', 'ladycop'); - -} diff --git a/examples/wip/autoscroll.js b/examples/wip/autoscroll.js deleted file mode 100644 index ae0f4a8a1..000000000 --- a/examples/wip/autoscroll.js +++ /dev/null @@ -1,37 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -var tilesprite; -var cursors; -var count = 0; - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var sprite; - -function create() { - - sprite = game.add.tileSprite(0, 0, 800, 600, 'starfield'); - sprite.autoScroll(0, 200); - - game.add.image(200, 200, 'mummy'); - - game.world.scale.set(2); - -} - -function update() { - -} - -function render() { - - // game.debug.text(sprite.frame, 32, 32); - -} diff --git a/examples/wip/bitmaptext littera.js b/examples/wip/bitmaptext littera.js deleted file mode 100644 index a2cacf457..000000000 --- a/examples/wip/bitmaptext littera.js +++ /dev/null @@ -1,14 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.bitmapFont('shortStack', 'assets/fonts/bitmapFonts/shortStack.png', 'assets/fonts/bitmapFonts/shortStack.fnt'); - -} - -function create() { - - game.add.bitmapText(32, 32, 'shortStack', 'This font was generated using the\nfree Littera web site\n\nhttp://kvazars.com/littera/', 32); - -} diff --git a/examples/wip/bitmaptext1.js b/examples/wip/bitmaptext1.js deleted file mode 100644 index 364fff96d..000000000 --- a/examples/wip/bitmaptext1.js +++ /dev/null @@ -1,35 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.bitmapFont('desyrel', 'assets/fonts/bitmapFonts/desyrel.png', 'assets/fonts/bitmapFonts/desyrel.xml', null, 0, -32); - game.load.bitmapFont('carrier', 'assets/fonts/bitmapFonts/carrier_command.png', 'assets/fonts/bitmapFonts/carrier_command.xml', null, 0, 24); - -} - -var text; -var text2; - -function create() { - - text = game.add.bitmapText(100, 100, 'carrier', 'Phaser and Pixi\nrocking!', 32); - - text2 = game.add.bitmapText(100, 300, 'desyrel', 'Phaser & Pixi\nrocking!', 64); - - game.input.onDown.add(change, this); - -} - -function change() { - - text.align = 'center'; - text2.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - // text.text = 'Phaser & Pixi\nrocking!\n' + Math.round(game.time.now); - -} diff --git a/examples/wip/bitmaptext2.js b/examples/wip/bitmaptext2.js deleted file mode 100644 index fc6f23b0a..000000000 --- a/examples/wip/bitmaptext2.js +++ /dev/null @@ -1,47 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('goldFont', 'assets/fonts/retroFonts/gold_font.png'); - game.load.image('bluePink', 'assets/fonts/retroFonts/bluepink_font.png'); - game.load.image('forgotten', 'assets/pics/forgotten_worlds.png'); - -} - -var font1; -var font2; -var image1; -var image2; - -function create() { - - font1 = game.add.retroFont('goldFont', 16, 16, "! :() ,?." + Phaser.RetroFont.TEXT_SET10, 20, 0, 0); - font1.text = "phaser brings you retro style bitmap fonts"; - - image1 = game.add.image(game.world.centerX, 48, font1); - image1.anchor.set(0.5); - - font2 = game.add.retroFont('bluePink', 32, 32, Phaser.RetroFont.TEXT_SET2, 10); - font2.setText("phaser 2\nin the house", true, 0, 8, Phaser.RetroFont.ALIGN_CENTER); - - image2 = game.add.image(game.world.centerX, 220, font2); - image2.anchor.set(0.5); - - game.add.image(0, game.height - 274, 'forgotten'); - - game.time.events.loop(Phaser.Timer.SECOND * 2, change, this); - -} - -function change() { - - image2.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - image2.rotation += (2 * game.time.physicsElapsed); - -} diff --git a/examples/wip/bitmaptext3.js b/examples/wip/bitmaptext3.js deleted file mode 100644 index 5f199adc9..000000000 --- a/examples/wip/bitmaptext3.js +++ /dev/null @@ -1,30 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('knightHawks', 'assets/fonts/retroFonts/KNIGHT3.png'); - -} - -var font; - -function create() { - - font = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET6, 10, 1, 1); - font.text = 'phaser was here'; - - for (var c = 0; c < 19; c++) - { - var i = game.add.image(game.world.centerX, c * 32, font); - i.tint = Math.random() * 0xFFFFFF; - i.anchor.set(0.5, 1); - } - -} - -function update() { - - font.text = "phaser x: " + game.input.x + " y: " + game.input.y; - -} diff --git a/examples/wip/blank text.js b/examples/wip/blank text.js deleted file mode 100644 index 5e5077eb8..000000000 --- a/examples/wip/blank text.js +++ /dev/null @@ -1,10 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - -function create() { - - var style = { font: "65px Arial", fill: "#ff0044", align: "center" }; - var text = game.add.text(game.world.centerX, game.world.centerY, "x", style); - - text.anchor.set(0.5); - -} \ No newline at end of file diff --git a/examples/wip/blendmodes.js b/examples/wip/blendmodes.js deleted file mode 100644 index b8fc2a710..000000000 --- a/examples/wip/blendmodes.js +++ /dev/null @@ -1,62 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('bg', 'assets/pics/color_wheel_swirl.png'); - game.load.image('pic', 'assets/pics/questar.png'); - game.load.image('mask1', 'assets/pics/mask-test.png'); - game.load.image('mask2', 'assets/pics/mask-test2.png'); - -} - -var pic; -var mask; - -function create() { - - var bmd = game.make.bitmapData(320, 200); - - // bmd.draw('pic'); - - bmd.alphaMask('pic', 'mask2'); - - pic = game.add.sprite(0, 0, bmd); - - // game.add.image(-200, 0, 'bg'); - - // mask = game.add.sprite(0, 0, 'mask1'); - - // pic = game.add.sprite(0, 0, 'pic'); - - // mask.addChild(pic); - - // pic.blendMode = Phaser.blendModes.NORMAL; - // pic.blendMode = Phaser.blendModes.ADD; - // pic.blendMode = Phaser.blendModes.MULTIPLY; - // pic.blendMode = Phaser.blendModes.SCREEN; - // mask.blendMode = Phaser.blendModes.OVERLAY; - // pic.blendMode = Phaser.blendModes.DARKEN; - // pic.blendMode = Phaser.blendModes.LIGHTEN; - // pic.blendMode = Phaser.blendModes.COLOR_DODGE; - // pic.blendMode = Phaser.blendModes.COLOR_BURN; - // pic.blendMode = Phaser.blendModes.HARD_LIGHT; - // pic.blendMode = Phaser.blendModes.SOFT_LIGHT; - // pic.blendMode = Phaser.blendModes.DIFFERENCE; - // pic.blendMode = Phaser.blendModes.EXCLUSION; - // pic.blendMode = Phaser.blendModes.HUE; - // pic.blendMode = PIXI.blendModes.SATURATION; - // pic.blendMode = Phaser.blendModes.COLOR; - // pic.blendMode = Phaser.blendModes.LUMINOSITY; - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/bmd.js b/examples/wip/bmd.js deleted file mode 100644 index 32e7be6ae..000000000 --- a/examples/wip/bmd.js +++ /dev/null @@ -1,36 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', '/phaser/examples/assets/pics/1984-nocooper-space.png'); - -} - -var image; -var bmd; - -function create() { - - console.log('pic box 11'); - - game.add.sprite(0, 0, 'pic'); - - bmd = game.add.bitmapData(800, 600); - bmd.context.fillStyle = 'rgba(255,0,0,1)'; - bmd.context.fillRect(0, 0, 300, 100); - - image = game.add.image(0, 100, bmd); - -} - -function update() { - - bmd.context.fillRect(game.input.x, game.input.y, 8, 8); - -} - -function render() { - - game.debug.text(game.input.x, 32, 32); - -} diff --git a/examples/wip/book/audio/explode.wav b/examples/wip/book/audio/explode.wav deleted file mode 100644 index 05cefd0c6..000000000 Binary files a/examples/wip/book/audio/explode.wav and /dev/null differ diff --git a/examples/wip/book/audio/shot.wav b/examples/wip/book/audio/shot.wav deleted file mode 100644 index 1ae178cba..000000000 Binary files a/examples/wip/book/audio/shot.wav and /dev/null differ diff --git a/examples/wip/book/audio/title.mp3 b/examples/wip/book/audio/title.mp3 deleted file mode 100644 index 2a31b561a..000000000 Binary files a/examples/wip/book/audio/title.mp3 and /dev/null differ diff --git a/examples/wip/book/fire.js b/examples/wip/book/fire.js deleted file mode 100644 index 4cbdc5b25..000000000 --- a/examples/wip/book/fire.js +++ /dev/null @@ -1,96 +0,0 @@ -PIXI.FireFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - resolution: { type: 'f2', value: { x: width, y: height }}, - mouse: { type: 'f2', value: { x: 0, y: 0 }}, - time: { type: 'f', value: 1 } - }; - - // http://glsl.heroku.com/e#11707.0 - - // Heroku shader conversion - this.fragmentSrc = [ - - "#ifdef GL_ES", - "precision mediump float;", - "#endif", - - "uniform float time;", - "uniform vec2 mouse;", - "uniform vec2 resolution;", - - "vec3 iResolution = vec3(resolution.x,resolution.y,100.);", - "vec4 iMouse = vec4(mouse.x,mouse.y,5.,5.);", - "float iGlobalTime = time;", - "uniform sampler2D iChannel0;", - - "// by @301z", - - "float rand(vec2 n) {", - "return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);", - "}", - - "// Genera ruido en función de las coordenadas del pixel", - "float noise(vec2 n) {", - "const vec2 d = vec2(0.0, 1.0);", - "vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));", - "return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);", - "}", - - "// Fractional Brownian Amplitude. Suma varias capas de ruido.", - "float fbm(vec2 n) {", - "float total = 0.0, amplitude = 1.0;", - "for (int i = 0; i < 4; i++) {", - "total += noise(n) * amplitude;", - "n += n;", - "amplitude *= 0.5;", - "}", - "return total;", - "}", - - "void main() {", - "// Colores", - "const vec3 c1 = vec3(0.5, 0.0, 0.1); // Rojo oscuro.", - "const vec3 c2 = vec3(0.9, 0.0, 0.0); // Rojo claro.", - "const vec3 c3 = vec3(0.2, 0.0, 0.0); // Rojo oscuro.", - "const vec3 c4 = vec3(1.0, 0.9, 0.0); // Amarillo.", - "const vec3 c5 = vec3(0.1); // Gris oscuro.", - "const vec3 c6 = vec3(0.9); // Gris claro.", - - "vec2 p = gl_FragCoord.xy * 8.0 / iResolution.xx; // Desfasa las coordenadas para que haya más cambio de un resultado a los colindantes.", - "float q = fbm(p - iGlobalTime * 0.1); // Ruido con offset para el movimiento.", - "vec2 r = vec2(fbm(p + q + iGlobalTime * 0.7 - p.x - p.y), fbm(p + q - iGlobalTime * 0.4));", - "vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);", - "gl_FragColor = vec4(c *", - "cos(1.57 * gl_FragCoord.y / iResolution.y), // Gradiente más ocuro arriba.", - "1.0);", - "}"]; - - - -} - -PIXI.FireFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.FireFilter.prototype.constructor = PIXI.FireFilter; - -Object.defineProperty(PIXI.FireFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.time.value; - }, - set: function(value) { - this.uniforms.time.value = value; - } -}); diff --git a/examples/wip/book/images/bullet.png b/examples/wip/book/images/bullet.png deleted file mode 100644 index ad04f6559..000000000 Binary files a/examples/wip/book/images/bullet.png and /dev/null differ diff --git a/examples/wip/book/images/explode.png b/examples/wip/book/images/explode.png deleted file mode 100644 index 0dd73247e..000000000 Binary files a/examples/wip/book/images/explode.png and /dev/null differ diff --git a/examples/wip/book/images/invader32x32x4.png b/examples/wip/book/images/invader32x32x4.png deleted file mode 100644 index 5d0409ccb..000000000 Binary files a/examples/wip/book/images/invader32x32x4.png and /dev/null differ diff --git a/examples/wip/book/images/landscape.png b/examples/wip/book/images/landscape.png deleted file mode 100644 index c34750eaa..000000000 Binary files a/examples/wip/book/images/landscape.png and /dev/null differ diff --git a/examples/wip/book/images/logo.png b/examples/wip/book/images/logo.png deleted file mode 100644 index ab34a5f77..000000000 Binary files a/examples/wip/book/images/logo.png and /dev/null differ diff --git a/examples/wip/book/images/robofont.png b/examples/wip/book/images/robofont.png deleted file mode 100644 index 5980813da..000000000 Binary files a/examples/wip/book/images/robofont.png and /dev/null differ diff --git a/examples/wip/book/images/robofont.xml b/examples/wip/book/images/robofont.xml deleted file mode 100644 index 095e141f0..000000000 --- a/examples/wip/book/images/robofont.xml +++ /dev/null @@ -1,100 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/wip/book/images/ship.png b/examples/wip/book/images/ship.png deleted file mode 100644 index de6128567..000000000 Binary files a/examples/wip/book/images/ship.png and /dev/null differ diff --git a/examples/wip/book/images/sky.png b/examples/wip/book/images/sky.png deleted file mode 100644 index fd815c12a..000000000 Binary files a/examples/wip/book/images/sky.png and /dev/null differ diff --git a/examples/wip/book/part1.html b/examples/wip/book/part1.html deleted file mode 100644 index 0cfcfc814..000000000 --- a/examples/wip/book/part1.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - Creating a game in Phaser, part 1 - - - - -
- - - - - \ No newline at end of file diff --git a/examples/wip/book/part2.html b/examples/wip/book/part2.html deleted file mode 100644 index 8ce054bab..000000000 --- a/examples/wip/book/part2.html +++ /dev/null @@ -1,335 +0,0 @@ - - - - - Creating a game in Phaser, part 2 - - - - - - - -
- - - - - \ No newline at end of file diff --git a/examples/wip/book/phaser.js b/examples/wip/book/phaser.js deleted file mode 100644 index aff10b285..000000000 --- a/examples/wip/book/phaser.js +++ /dev/null @@ -1,40026 +0,0 @@ -!function(root, factory) { - if (typeof define === "function" && define.amd) { - define(factory); - } else if (typeof exports === "object") { - module.exports = factory(); - } else { - root.Phaser = factory(); - } -}(this, function() { -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* @overview -* -* Phaser - http://www.phaser.io -* -* v1.1.3 - Built at: Thu Nov 21 2013 05:29:46 -* -* By Richard Davey http://www.photonstorm.com @photonstorm -* -* A feature-packed 2D HTML5 game framework born from the smouldering pits of Flixel and -* constructed via plenty of blood, sweat, tears and coffee by Richard Davey (@photonstorm). -* -* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com/ @Doormat23. -* -* Follow Phaser development progress at http://www.photonstorm.com -* -* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from both which Phaser -* and my love of game development originate. -* -* "If you want your children to be intelligent, read them fairy tales." -* "If you want them to be more intelligent, read them more fairy tales." -* -- Albert Einstein -*/ - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * @module PIXI - */ -var PIXI = PIXI || {}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* @namespace Phaser -*/ -var Phaser = Phaser || { - - VERSION: '1.1.3', - DEV_VERSION: '1.1.3', - GAMES: [], - AUTO: 0, - CANVAS: 1, - WEBGL: 2, - - SPRITE: 0, - BUTTON: 1, - BULLET: 2, - GRAPHICS: 3, - TEXT: 4, - TILESPRITE: 5, - BITMAPTEXT: 6, - GROUP: 7, - RENDERTEXTURE: 8, - TILEMAP: 9, - TILEMAPLAYER: 10, - EMITTER: 11, - POLYGON: 12, - BITMAPDATA: 13, - CANVAS_FILTER: 14, - WEBGL_FILTER: 15, - - NONE: 0, - LEFT: 1, - RIGHT: 2, - UP: 3, - DOWN: 4 - - }; - -PIXI.InteractionManager = function (dummy) { - // We don't need this in Pixi, so we've removed it to save space - // however the Stage object expects a reference to it, so here is a dummy entry. -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* @class Phaser.Utils -* @static -*/ -Phaser.Utils = { - - /** - * A standard Fisher-Yates Array shuffle implementation. - * @method Phaser.Utils.shuffle - * @param {array} array - The array to shuffle. - * @return {array} The shuffled array. - */ - shuffle: function (array) { - - for (var i = array.length - 1; i > 0; i--) - { - var j = Math.floor(Math.random() * (i + 1)); - var temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - return array; - - }, - - /** - * Javascript string pad http://www.webtoolkit.info/. - * pad = the string to pad it out with (defaults to a space) - * dir = 1 (left), 2 (right), 3 (both) - * @method Phaser.Utils.pad - * @param {string} str - The target string. - * @param {number} len - Description. - * @param {number} pad - the string to pad it out with (defaults to a space). - * @param {number} [dir=3] the direction dir = 1 (left), 2 (right), 3 (both). - * @return {string} The padded string - */ - pad: function (str, len, pad, dir) { - - if (typeof(len) == "undefined") { var len = 0; } - if (typeof(pad) == "undefined") { var pad = ' '; } - if (typeof(dir) == "undefined") { var dir = 3; } - - if (len + 1 >= str.length) - { - switch (dir) - { - case 1: - str = Array(len + 1 - str.length).join(pad) + str; - break; - - case 3: - var right = Math.ceil((padlen = len - str.length) / 2); - var left = padlen - right; - str = Array(left+1).join(pad) + str + Array(right+1).join(pad); - break; - - default: - str = str + Array(len + 1 - str.length).join(pad); - break; - } - } - - return str; - - }, - - /** - * This is a slightly modified version of jQuery.isPlainObject. A plain object is an object whose internal class property is [object Object]. - * @method Phaser.Utils.isPlainObject - * @param {object} obj - The object to inspect. - * @return {boolean} - true if the object is plain, otherwise false. - */ - isPlainObject: function (obj) { - - // Not plain objects: - // - Any object or value whose internal [[Class]] property is not "[object Object]" - // - DOM nodes - // - window - if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window) - { - return false; - } - - // Support: Firefox <20 - // The try/catch suppresses exceptions thrown when attempting to access - // the "constructor" property of certain host objects, ie. |window.location| - // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 - try { - if (obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) - { - return false; - } - } catch (e) { - return false; - } - - // If the function hasn't returned already, we're confident that - // |obj| is a plain object, created by {} or constructed with new Object - return true; - }, - - - // deep, target, objects to copy to the target object - // This is a slightly modified version of {@link http://api.jquery.com/jQuery.extend/|jQuery.extend} - // deep (boolean) - // target (object to add to) - // objects ... (objects to recurse and copy from) - - /** - * This is a slightly modified version of http://api.jquery.com/jQuery.extend/ - * @method Phaser.Utils.extend - * @param {boolean} deep - Perform a deep copy? - * @param {object} target - The target object to copy to. - * @return {object} The extended object. - */ - extend: function () { - - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if (typeof target === "boolean") - { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // extend Phaser if only one argument is passed - if (length === i) - { - target = this; - --i; - } - - for ( ; i < length; i++ ) - { - // Only deal with non-null/undefined values - if ((options = arguments[i]) != null) - { - // Extend the base object - for (name in options) - { - src = target[name]; - copy = options[name]; - - // Prevent never-ending loop - if (target === copy) - { - continue; - } - - // Recurse if we're merging plain objects or arrays - if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) - { - if (copyIsArray) - { - copyIsArray = false; - clone = src && Array.isArray(src) ? src : []; - } - else - { - clone = src && Phaser.Utils.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[name] = Phaser.Utils.extend(deep, clone, copy); - - // Don't bring in undefined values - } - else if (copy !== undefined) - { - target[name] = copy; - } - } - } - } - - // Return the modified object - return target; - } - -}; - -// Global functions that PIXI needs - -(function() { - var consoleDisabled = false; - if (consoleDisabled) { - window.console = undefined; - } - if (window.console == undefined) { - window.console = { - debug: function() { - return true; - }, - info: function() { - return false; - }, - warn: function() { - return false; - }, - log: function() { - return false; - } - } - } - debug = (function(args) { - window.console.debug(args); - }); - info = (function(args) { - window.console.info(args); - }); - warn = (function(args) { - window.console.warn(args); - }); - log = (function(args) { - window.console.log(args); - }); -})(); - -/** -* Converts a hex color number to an [R, G, B] array -* -* @param {number} hex -* @return {array} -*/ -function HEXtoRGB(hex) { - return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255]; -} - -/** -* A polyfill for Function.prototype.bind -*/ -if (typeof Function.prototype.bind != 'function') { - Function.prototype.bind = (function () { - var slice = Array.prototype.slice; - return function (thisArg) { - var target = this, boundArgs = slice.call(arguments, 1); - - if (typeof target != 'function') throw new TypeError(); - - function bound() { - var args = boundArgs.concat(slice.call(arguments)); - target.apply(this instanceof bound ? this : thisArg, args); - } - - bound.prototype = (function F(proto) { - proto && (F.prototype = proto); - if (!(this instanceof F)) return new F; - })(target.prototype); - - return bound; - }; - })(); -} - - - - -/* - * A lighter version of the rad gl-matrix created by Brandon Jones, Colin MacKenzie IV - * you both rock! - */ - -function determineMatrixArrayType() { - PIXI.Matrix = (typeof Float32Array !== 'undefined') ? Float32Array : Array; - return PIXI.Matrix; -} - -determineMatrixArrayType(); - -PIXI.mat3 = {}; - -PIXI.mat3.create = function() -{ - var matrix = new PIXI.Matrix(9); - - matrix[0] = 1; - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 0; - matrix[4] = 1; - matrix[5] = 0; - matrix[6] = 0; - matrix[7] = 0; - matrix[8] = 1; - - return matrix; -} - - -PIXI.mat3.identity = function(matrix) -{ - matrix[0] = 1; - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 0; - matrix[4] = 1; - matrix[5] = 0; - matrix[6] = 0; - matrix[7] = 0; - matrix[8] = 1; - - return matrix; -} - - -PIXI.mat4 = {}; - -PIXI.mat4.create = function() -{ - var matrix = new PIXI.Matrix(16); - - matrix[0] = 1; - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 0; - matrix[4] = 0; - matrix[5] = 1; - matrix[6] = 0; - matrix[7] = 0; - matrix[8] = 0; - matrix[9] = 0; - matrix[10] = 1; - matrix[11] = 0; - matrix[12] = 0; - matrix[13] = 0; - matrix[14] = 0; - matrix[15] = 1; - - return matrix; -} - -PIXI.mat3.multiply = function (mat, mat2, dest) -{ - if (!dest) { dest = mat; } - - // Cache the matrix values (makes for huge speed increases!) - var a00 = mat[0], a01 = mat[1], a02 = mat[2], - a10 = mat[3], a11 = mat[4], a12 = mat[5], - a20 = mat[6], a21 = mat[7], a22 = mat[8], - - b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], - b10 = mat2[3], b11 = mat2[4], b12 = mat2[5], - b20 = mat2[6], b21 = mat2[7], b22 = mat2[8]; - - dest[0] = b00 * a00 + b01 * a10 + b02 * a20; - dest[1] = b00 * a01 + b01 * a11 + b02 * a21; - dest[2] = b00 * a02 + b01 * a12 + b02 * a22; - - dest[3] = b10 * a00 + b11 * a10 + b12 * a20; - dest[4] = b10 * a01 + b11 * a11 + b12 * a21; - dest[5] = b10 * a02 + b11 * a12 + b12 * a22; - - dest[6] = b20 * a00 + b21 * a10 + b22 * a20; - dest[7] = b20 * a01 + b21 * a11 + b22 * a21; - dest[8] = b20 * a02 + b21 * a12 + b22 * a22; - - return dest; -} - -PIXI.mat3.clone = function(mat) -{ - var matrix = new PIXI.Matrix(9); - - matrix[0] = mat[0]; - matrix[1] = mat[1]; - matrix[2] = mat[2]; - matrix[3] = mat[3]; - matrix[4] = mat[4]; - matrix[5] = mat[5]; - matrix[6] = mat[6]; - matrix[7] = mat[7]; - matrix[8] = mat[8]; - - return matrix; -} - -PIXI.mat3.transpose = function (mat, dest) -{ - // If we are transposing ourselves we can skip a few steps but have to cache some values - if (!dest || mat === dest) { - var a01 = mat[1], a02 = mat[2], - a12 = mat[5]; - - mat[1] = mat[3]; - mat[2] = mat[6]; - mat[3] = a01; - mat[5] = mat[7]; - mat[6] = a02; - mat[7] = a12; - return mat; - } - - dest[0] = mat[0]; - dest[1] = mat[3]; - dest[2] = mat[6]; - dest[3] = mat[1]; - dest[4] = mat[4]; - dest[5] = mat[7]; - dest[6] = mat[2]; - dest[7] = mat[5]; - dest[8] = mat[8]; - return dest; -} - -PIXI.mat3.toMat4 = function (mat, dest) -{ - if (!dest) { dest = PIXI.mat4.create(); } - - dest[15] = 1; - dest[14] = 0; - dest[13] = 0; - dest[12] = 0; - - dest[11] = 0; - dest[10] = mat[8]; - dest[9] = mat[7]; - dest[8] = mat[6]; - - dest[7] = 0; - dest[6] = mat[5]; - dest[5] = mat[4]; - dest[4] = mat[3]; - - dest[3] = 0; - dest[2] = mat[2]; - dest[1] = mat[1]; - dest[0] = mat[0]; - - return dest; -} - - -///// - - -PIXI.mat4.create = function() -{ - var matrix = new PIXI.Matrix(16); - - matrix[0] = 1; - matrix[1] = 0; - matrix[2] = 0; - matrix[3] = 0; - matrix[4] = 0; - matrix[5] = 1; - matrix[6] = 0; - matrix[7] = 0; - matrix[8] = 0; - matrix[9] = 0; - matrix[10] = 1; - matrix[11] = 0; - matrix[12] = 0; - matrix[13] = 0; - matrix[14] = 0; - matrix[15] = 1; - - return matrix; -} - -PIXI.mat4.transpose = function (mat, dest) -{ - // If we are transposing ourselves we can skip a few steps but have to cache some values - if (!dest || mat === dest) - { - var a01 = mat[1], a02 = mat[2], a03 = mat[3], - a12 = mat[6], a13 = mat[7], - a23 = mat[11]; - - mat[1] = mat[4]; - mat[2] = mat[8]; - mat[3] = mat[12]; - mat[4] = a01; - mat[6] = mat[9]; - mat[7] = mat[13]; - mat[8] = a02; - mat[9] = a12; - mat[11] = mat[14]; - mat[12] = a03; - mat[13] = a13; - mat[14] = a23; - return mat; - } - - dest[0] = mat[0]; - dest[1] = mat[4]; - dest[2] = mat[8]; - dest[3] = mat[12]; - dest[4] = mat[1]; - dest[5] = mat[5]; - dest[6] = mat[9]; - dest[7] = mat[13]; - dest[8] = mat[2]; - dest[9] = mat[6]; - dest[10] = mat[10]; - dest[11] = mat[14]; - dest[12] = mat[3]; - dest[13] = mat[7]; - dest[14] = mat[11]; - dest[15] = mat[15]; - return dest; -} - -PIXI.mat4.multiply = function (mat, mat2, dest) -{ - if (!dest) { dest = mat; } - - // Cache the matrix values (makes for huge speed increases!) - var a00 = mat[ 0], a01 = mat[ 1], a02 = mat[ 2], a03 = mat[3]; - var a10 = mat[ 4], a11 = mat[ 5], a12 = mat[ 6], a13 = mat[7]; - var a20 = mat[ 8], a21 = mat[ 9], a22 = mat[10], a23 = mat[11]; - var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15]; - - // Cache only the current line of the second matrix - var b0 = mat2[0], b1 = mat2[1], b2 = mat2[2], b3 = mat2[3]; - dest[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - dest[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - dest[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - dest[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - b0 = mat2[4]; - b1 = mat2[5]; - b2 = mat2[6]; - b3 = mat2[7]; - dest[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - dest[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - dest[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - dest[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - b0 = mat2[8]; - b1 = mat2[9]; - b2 = mat2[10]; - b3 = mat2[11]; - dest[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - dest[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - dest[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - dest[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - b0 = mat2[12]; - b1 = mat2[13]; - b2 = mat2[14]; - b3 = mat2[15]; - dest[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30; - dest[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31; - dest[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32; - dest[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33; - - return dest; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. - * - * @class Point - * @constructor - * @param x {Number} position of the point - * @param y {Number} position of the point - */ -PIXI.Point = function(x, y) -{ - /** - * @property x - * @type Number - * @default 0 - */ - this.x = x || 0; - - /** - * @property y - * @type Number - * @default 0 - */ - this.y = y || 0; -} - -/** - * Creates a clone of this point - * - * @method clone - * @return {Point} a copy of the point - */ -PIXI.Point.prototype.clone = function() -{ - return new PIXI.Point(this.x, this.y); -} - -// constructor -PIXI.Point.prototype.constructor = PIXI.Point; - - -/** - * @author Mat Groves http://matgroves.com/ - */ - -/** - * the Rectangle object is an area defined by its position, as indicated by its top-left corner point (x, y) and by its width and its height. - * - * @class Rectangle - * @constructor - * @param x {Number} The X coord of the upper-left corner of the rectangle - * @param y {Number} The Y coord of the upper-left corner of the rectangle - * @param width {Number} The overall width of this rectangle - * @param height {Number} The overall height of this rectangle - */ -PIXI.Rectangle = function(x, y, width, height) -{ - /** - * @property x - * @type Number - * @default 0 - */ - this.x = x || 0; - - /** - * @property y - * @type Number - * @default 0 - */ - this.y = y || 0; - - /** - * @property width - * @type Number - * @default 0 - */ - this.width = width || 0; - - /** - * @property height - * @type Number - * @default 0 - */ - this.height = height || 0; -} - -/** - * Creates a clone of this Rectangle - * - * @method clone - * @return {Rectangle} a copy of the rectangle - */ -PIXI.Rectangle.prototype.clone = function() -{ - return new PIXI.Rectangle(this.x, this.y, this.width, this.height); -} - -/** - * Checks if the x, and y coords passed to this function are contained within this Rectangle - * - * @method contains - * @param x {Number} The X coord of the point to test - * @param y {Number} The Y coord of the point to test - * @return {Boolean} if the x/y coords are within this Rectangle - */ -PIXI.Rectangle.prototype.contains = function(x, y) -{ - if(this.width <= 0 || this.height <= 0) - return false; - - var x1 = this.x; - if(x >= x1 && x <= x1 + this.width) - { - var y1 = this.y; - - if(y >= y1 && y <= y1 + this.height) - { - return true; - } - } - - return false; -} - -// constructor -PIXI.Rectangle.prototype.constructor = PIXI.Rectangle; - - -/** - * @author Adrien Brault - */ - -/** - * @class Polygon - * @constructor - * @param points* {Array|Array|Point...|Number...} This can be an array of Points that form the polygon, - * a flat array of numbers that will be interpreted as [x,y, x,y, ...], or the arguments passed can be - * all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the - * arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are - * Numbers. - */ -PIXI.Polygon = function(points) -{ - //if points isn't an array, use arguments as the array - if(!(points instanceof Array)) - points = Array.prototype.slice.call(arguments); - - //if this is a flat array of numbers, convert it to points - if(typeof points[0] === 'number') { - var p = []; - for(var i = 0, il = points.length; i < il; i+=2) { - p.push( - new PIXI.Point(points[i], points[i + 1]) - ); - } - - points = p; - } - - this.points = points; -} - -/** - * Creates a clone of this polygon - * - * @method clone - * @return {Polygon} a copy of the polygon - */ -PIXI.Polygon.prototype.clone = function() -{ - var points = []; - for (var i=0; i y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); - - if(intersect) inside = !inside; - } - - return inside; -} - -// constructor -PIXI.Polygon.prototype.constructor = PIXI.Polygon; - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * The base class for all objects that are rendered on the screen. - * - * @class DisplayObject - * @constructor - */ -PIXI.DisplayObject = function() -{ - this.last = this; - this.first = this; - /** - * The coordinate of the object relative to the local coordinates of the parent. - * - * @property position - * @type Point - */ - this.position = new PIXI.Point(); - - /** - * The scale factor of the object. - * - * @property scale - * @type Point - */ - this.scale = new PIXI.Point(1,1);//{x:1, y:1}; - - /** - * The pivot point of the displayObject that it rotates around - * - * @property pivot - * @type Point - */ - this.pivot = new PIXI.Point(0,0); - - /** - * The rotation of the object in radians. - * - * @property rotation - * @type Number - */ - this.rotation = 0; - - /** - * The opacity of the object. - * - * @property alpha - * @type Number - */ - this.alpha = 1; - - /** - * The visibility of the object. - * - * @property visible - * @type Boolean - */ - this.visible = true; - - /** - * This is the defined area that will pick up mouse / touch events. It is null by default. - * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children) - * - * @property hitArea - * @type Rectangle|Circle|Ellipse|Polygon - */ - this.hitArea = null; - - /** - * This is used to indicate if the displayObject should display a mouse hand cursor on rollover - * - * @property buttonMode - * @type Boolean - */ - this.buttonMode = false; - - /** - * Can this object be rendered - * - * @property renderable - * @type Boolean - */ - this.renderable = false; - - /** - * [read-only] The display object container that contains this display object. - * - * @property parent - * @type DisplayObjectContainer - * @readOnly - */ - this.parent = null; - - /** - * [read-only] The stage the display object is connected to, or undefined if it is not connected to the stage. - * - * @property stage - * @type Stage - * @readOnly - */ - this.stage = null; - - /** - * [read-only] The multiplied alpha of the displayobject - * - * @property worldAlpha - * @type Number - * @readOnly - */ - this.worldAlpha = 1; - - /** - * [read-only] Whether or not the object is interactive, do not toggle directly! use the `interactive` property - * - * @property _interactive - * @type Boolean - * @readOnly - * @private - */ - this._interactive = false; - - /** - * [read-only] Current transform of the object based on world (parent) factors - * - * @property worldTransform - * @type Mat3 - * @readOnly - * @private - */ - this.worldTransform = PIXI.mat3.create()//mat3.identity(); - - /** - * [read-only] Current transform of the object locally - * - * @property localTransform - * @type Mat3 - * @readOnly - * @private - */ - this.localTransform = PIXI.mat3.create()//mat3.identity(); - - /** - * [NYI] Unkown - * - * @property color - * @type Array<> - * @private - */ - this.color = []; - - /** - * [NYI] Holds whether or not this object is dynamic, for rendering optimization - * - * @property dynamic - * @type Boolean - * @private - */ - this.dynamic = true; - - // chach that puppy! - this._sr = 0; - this._cr = 1; - - - this.filterArea = new PIXI.Rectangle(0,0,1,1); - - /* - * MOUSE Callbacks - */ - - /** - * A callback that is used when the users clicks on the displayObject with their mouse - * @method click - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the user clicks the mouse down over the sprite - * @method mousedown - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the user releases the mouse that was over the displayObject - * for this callback to be fired the mouse must have been pressed down over the displayObject - * @method mouseup - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the user releases the mouse that was over the displayObject but is no longer over the displayObject - * for this callback to be fired, The touch must have started over the displayObject - * @method mouseupoutside - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the users mouse rolls over the displayObject - * @method mouseover - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the users mouse leaves the displayObject - * @method mouseout - * @param interactionData {InteractionData} - */ - - - /* - * TOUCH Callbacks - */ - - /** - * A callback that is used when the users taps on the sprite with their finger - * basically a touch version of click - * @method tap - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the user touch's over the displayObject - * @method touchstart - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the user releases a touch over the displayObject - * @method touchend - * @param interactionData {InteractionData} - */ - - /** - * A callback that is used when the user releases the touch that was over the displayObject - * for this callback to be fired, The touch must have started over the sprite - * @method touchendoutside - * @param interactionData {InteractionData} - */ -} - -// constructor -PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject; - -/** - * [Deprecated] Indicates if the sprite will have touch and mouse interactivity. It is false by default - * Instead of using this function you can now simply set the interactive property to true or false - * - * @method setInteractive - * @param interactive {Boolean} - * @deprecated Simply set the `interactive` property directly - */ -PIXI.DisplayObject.prototype.setInteractive = function(interactive) -{ - this.interactive = interactive; -} - -/** - * Indicates if the sprite will have touch and mouse interactivity. It is false by default - * - * @property interactive - * @type Boolean - * @default false - */ -Object.defineProperty(PIXI.DisplayObject.prototype, 'interactive', { - get: function() { - return this._interactive; - }, - set: function(value) { - this._interactive = value; - - // TODO more to be done here.. - // need to sort out a re-crawl! - if(this.stage)this.stage.dirty = true; - } -}); - -/** - * Sets a mask for the displayObject. A mask is an object that limits the visibility of an object to the shape of the mask applied to it. - * In PIXI a regular mask must be a PIXI.Ggraphics object. This allows for much faster masking in canvas as it utilises shape clipping. - * To remove a mask, set this property to null. - * - * @property mask - * @type Graphics - */ -Object.defineProperty(PIXI.DisplayObject.prototype, 'mask', { - get: function() { - return this._mask; - }, - set: function(value) { - - - if(value) - { - if(this._mask) - { - value.start = this._mask.start; - value.end = this._mask.end; - } - else - { - this.addFilter(value); - value.renderable = false; - } - } - else - { - this.removeFilter(this._mask); - this._mask.renderable = true; - } - - this._mask = value; - } -}); - -/** - * Sets the filters for the displayObject. - * * IMPORTANT: This is a webGL only feature and will be ignored by the canvas renderer. - * To remove filters simply set this property to 'null' - * @property filters - * @type Array An array of filters - */ -Object.defineProperty(PIXI.DisplayObject.prototype, 'filters', { - get: function() { - return this._filters; - }, - set: function(value) { - - if(value) - { - if(this._filters)this.removeFilter(this._filters); - this.addFilter(value); - - // now put all the passes in one place.. - var passes = []; - for (var i = 0; i < value.length; i++) - { - var filterPasses = value[i].passes; - for (var j = 0; j < filterPasses.length; j++) - { - passes.push(filterPasses[j]); - }; - }; - - value.start.filterPasses = passes; - } - else - { - if(this._filters)this.removeFilter(this._filters); - } - - this._filters = value; - - - - - } -}); - -/* - * Adds a filter to this displayObject - * - * @method addFilter - * @param mask {Graphics} the graphics object to use as a filter - * @private - */ -PIXI.DisplayObject.prototype.addFilter = function(data) -{ - - // insert a filter block.. - // TODO Onject pool thease bad boys.. - var start = new PIXI.FilterBlock(); - var end = new PIXI.FilterBlock(); - - data.start = start; - data.end = end; - - start.data = data; - end.data = data; - - start.first = start.last = this; - end.first = end.last = this; - - start.open = true; - - start.target = this; - - /* - * insert start - */ - - var childFirst = start - var childLast = start - var nextObject; - var previousObject; - - previousObject = this.first._iPrev; - - if(previousObject) - { - nextObject = previousObject._iNext; - childFirst._iPrev = previousObject; - previousObject._iNext = childFirst; - } - else - { - nextObject = this; - } - - if(nextObject) - { - nextObject._iPrev = childLast; - childLast._iNext = nextObject; - } - - - // now insert the end filter block.. - - /* - * insert end filter - */ - var childFirst = end - var childLast = end - var nextObject = null; - var previousObject = null; - - previousObject = this.last; - nextObject = previousObject._iNext; - - if(nextObject) - { - nextObject._iPrev = childLast; - childLast._iNext = nextObject; - } - - childFirst._iPrev = previousObject; - previousObject._iNext = childFirst; - - var updateLast = this; - - var prevLast = this.last; - while(updateLast) - { - if(updateLast.last == prevLast) - { - updateLast.last = end; - } - updateLast = updateLast.parent; - } - - this.first = start; - - // if webGL... - if(this.__renderGroup) - { - this.__renderGroup.addFilterBlocks(start, end); - } - -} - -/* - * Removes the filter to this displayObject - * - * @method removeFilter - * @private - */ -PIXI.DisplayObject.prototype.removeFilter = function(data) -{ - //if(!this.filter)return; - //this.filter = false; - console.log("YUOIO") - // modify the list.. - var startBlock = data.start; - - - var nextObject = startBlock._iNext; - var previousObject = startBlock._iPrev; - - if(nextObject)nextObject._iPrev = previousObject; - if(previousObject)previousObject._iNext = nextObject; - - this.first = startBlock._iNext; - - // remove the end filter - var lastBlock = data.end; - - var nextObject = lastBlock._iNext; - var previousObject = lastBlock._iPrev; - - if(nextObject)nextObject._iPrev = previousObject; - previousObject._iNext = nextObject; - - // this is always true too! - var tempLast = lastBlock._iPrev; - // need to make sure the parents last is updated too - var updateLast = this; - while(updateLast.last == lastBlock) - { - updateLast.last = tempLast; - updateLast = updateLast.parent; - if(!updateLast)break; - } - - // if webGL... - if(this.__renderGroup) - { - this.__renderGroup.removeFilterBlocks(startBlock, lastBlock); - } -} - -/* - * Updates the object transform for rendering - * - * @method updateTransform - * @private - */ -PIXI.DisplayObject.prototype.updateTransform = function() -{ - // TODO OPTIMIZE THIS!! with dirty - if(this.rotation !== this.rotationCache) - { - this.rotationCache = this.rotation; - this._sr = Math.sin(this.rotation); - this._cr = Math.cos(this.rotation); - } - - var localTransform = this.localTransform; - var parentTransform = this.parent.worldTransform; - var worldTransform = this.worldTransform; - //console.log(localTransform) - localTransform[0] = this._cr * this.scale.x; - localTransform[1] = -this._sr * this.scale.y - localTransform[3] = this._sr * this.scale.x; - localTransform[4] = this._cr * this.scale.y; - - // TODO --> do we even need a local matrix??? - - var px = this.pivot.x; - var py = this.pivot.y; - - // Cache the matrix values (makes for huge speed increases!) - var a00 = localTransform[0], a01 = localTransform[1], a02 = this.position.x - localTransform[0] * px - py * localTransform[1], - a10 = localTransform[3], a11 = localTransform[4], a12 = this.position.y - localTransform[4] * py - px * localTransform[3], - - b00 = parentTransform[0], b01 = parentTransform[1], b02 = parentTransform[2], - b10 = parentTransform[3], b11 = parentTransform[4], b12 = parentTransform[5]; - - localTransform[2] = a02 - localTransform[5] = a12 - - worldTransform[0] = b00 * a00 + b01 * a10; - worldTransform[1] = b00 * a01 + b01 * a11; - worldTransform[2] = b00 * a02 + b01 * a12 + b02; - - worldTransform[3] = b10 * a00 + b11 * a10; - worldTransform[4] = b10 * a01 + b11 * a11; - worldTransform[5] = b10 * a02 + b11 * a12 + b12; - - // because we are using affine transformation, we can optimise the matrix concatenation process.. wooo! - // mat3.multiply(this.localTransform, this.parent.worldTransform, this.worldTransform); - this.worldAlpha = this.alpha * this.parent.worldAlpha; - - this.vcount = PIXI.visibleCount; - -} - -PIXI.visibleCount = 0; -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * A DisplayObjectContainer represents a collection of display objects. - * It is the base class of all display objects that act as a container for other objects. - * - * @class DisplayObjectContainer - * @extends DisplayObject - * @constructor - */ -PIXI.DisplayObjectContainer = function() -{ - PIXI.DisplayObject.call( this ); - - /** - * [read-only] The of children of this container. - * - * @property children - * @type Array - * @readOnly - */ - this.children = []; -} - -// constructor -PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype ); -PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer; - -/** - * Adds a child to the container. - * - * @method addChild - * @param child {DisplayObject} The DisplayObject to add to the container - */ -PIXI.DisplayObjectContainer.prototype.addChild = function(child) -{ - if(child.parent != undefined) - { - - //// COULD BE THIS??? - child.parent.removeChild(child); - // return; - } - - child.parent = this; - - this.children.push(child); - - // update the stage refference.. - - if(this.stage) - { - var tmpChild = child; - do - { - if(tmpChild.interactive)this.stage.dirty = true; - tmpChild.stage = this.stage; - tmpChild = tmpChild._iNext; - } - while(tmpChild) - } - - // LINKED LIST // - - // modify the list.. - var childFirst = child.first - var childLast = child.last; - var nextObject; - var previousObject; - - // this could be wrong if there is a filter?? - if(this._filters || this._mask) - { - previousObject = this.last._iPrev; - } - else - { - previousObject = this.last; - } - - nextObject = previousObject._iNext; - - // always true in this case - // need to make sure the parents last is updated too - var updateLast = this; - var prevLast = previousObject; - - while(updateLast) - { - if(updateLast.last == prevLast) - { - updateLast.last = child.last; - } - updateLast = updateLast.parent; - } - - if(nextObject) - { - nextObject._iPrev = childLast; - childLast._iNext = nextObject; - } - - childFirst._iPrev = previousObject; - previousObject._iNext = childFirst; - - // need to remove any render groups.. - if(this.__renderGroup) - { - // being used by a renderTexture.. if it exists then it must be from a render texture; - if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child); - // add them to the new render group.. - this.__renderGroup.addDisplayObjectAndChildren(child); - } - -} - -/** - * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown - * - * @method addChildAt - * @param child {DisplayObject} The child to add - * @param index {Number} The index to place the child in - */ -PIXI.DisplayObjectContainer.prototype.addChildAt = function(child, index) -{ - if(index >= 0 && index <= this.children.length) - { - if(child.parent != undefined) - { - child.parent.removeChild(child); - } - child.parent = this; - - if(this.stage) - { - var tmpChild = child; - do - { - if(tmpChild.interactive)this.stage.dirty = true; - tmpChild.stage = this.stage; - tmpChild = tmpChild._iNext; - } - while(tmpChild) - } - - // modify the list.. - var childFirst = child.first; - var childLast = child.last; - var nextObject; - var previousObject; - - if(index == this.children.length) - { - previousObject = this.last; - var updateLast = this; - var prevLast = this.last; - while(updateLast) - { - if(updateLast.last == prevLast) - { - updateLast.last = child.last; - } - updateLast = updateLast.parent; - } - } - else if(index == 0) - { - previousObject = this; - } - else - { - previousObject = this.children[index-1].last; - } - - nextObject = previousObject._iNext; - - // always true in this case - if(nextObject) - { - nextObject._iPrev = childLast; - childLast._iNext = nextObject; - } - - childFirst._iPrev = previousObject; - previousObject._iNext = childFirst; - - this.children.splice(index, 0, child); - // need to remove any render groups.. - if(this.__renderGroup) - { - // being used by a renderTexture.. if it exists then it must be from a render texture; - if(child.__renderGroup)child.__renderGroup.removeDisplayObjectAndChildren(child); - // add them to the new render group.. - this.__renderGroup.addDisplayObjectAndChildren(child); - } - - } - else - { - throw new Error(child + " The index "+ index +" supplied is out of bounds " + this.children.length); - } -} - -/** - * [NYI] Swaps the depth of 2 displayObjects - * - * @method swapChildren - * @param child {DisplayObject} - * @param child2 {DisplayObject} - * @private - */ -PIXI.DisplayObjectContainer.prototype.swapChildren = function(child, child2) -{ - /* - * this funtion needs to be recoded.. - * can be done a lot faster.. - */ - return; - - // need to fix this function :/ - /* - // TODO I already know this?? - var index = this.children.indexOf( child ); - var index2 = this.children.indexOf( child2 ); - - if ( index !== -1 && index2 !== -1 ) - { - // cool - - /* - if(this.stage) - { - // this is to satisfy the webGL batching.. - // TODO sure there is a nicer way to achieve this! - this.stage.__removeChild(child); - this.stage.__removeChild(child2); - - this.stage.__addChild(child); - this.stage.__addChild(child2); - } - - // swap the positions.. - this.children[index] = child2; - this.children[index2] = child; - - } - else - { - throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this); - }*/ -} - -/** - * Returns the Child at the specified index - * - * @method getChildAt - * @param index {Number} The index to get the child from - */ -PIXI.DisplayObjectContainer.prototype.getChildAt = function(index) -{ - if(index >= 0 && index < this.children.length) - { - return this.children[index]; - } - else - { - throw new Error(child + " Both the supplied DisplayObjects must be a child of the caller " + this); - } -} - -/** - * Removes a child from the container. - * - * @method removeChild - * @param child {DisplayObject} The DisplayObject to remove - */ -PIXI.DisplayObjectContainer.prototype.removeChild = function(child) -{ - var index = this.children.indexOf( child ); - if ( index !== -1 ) - { - // unlink // - // modify the list.. - var childFirst = child.first; - var childLast = child.last; - - var nextObject = childLast._iNext; - var previousObject = childFirst._iPrev; - - if(nextObject)nextObject._iPrev = previousObject; - previousObject._iNext = nextObject; - - if(this.last == childLast) - { - var tempLast = childFirst._iPrev; - // need to make sure the parents last is updated too - var updateLast = this; - while(updateLast.last == childLast.last) - { - updateLast.last = tempLast; - updateLast = updateLast.parent; - if(!updateLast)break; - } - } - - childLast._iNext = null; - childFirst._iPrev = null; - - // update the stage reference.. - if(this.stage) - { - var tmpChild = child; - do - { - if(tmpChild.interactive)this.stage.dirty = true; - tmpChild.stage = null; - tmpChild = tmpChild._iNext; - } - while(tmpChild) - } - - // webGL trim - if(child.__renderGroup) - { - child.__renderGroup.removeDisplayObjectAndChildren(child); - } - - child.parent = undefined; - this.children.splice( index, 1 ); - } - else - { - throw new Error(child + " The supplied DisplayObject must be a child of the caller " + this); - } -} - -/* - * Updates the container's children's transform for rendering - * - * @method updateTransform - * @private - */ -PIXI.DisplayObjectContainer.prototype.updateTransform = function() -{ - if(!this.visible)return; - - PIXI.DisplayObject.prototype.updateTransform.call( this ); - - for(var i=0,j=this.children.length; i 1)ratio = 1; - - var perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y); - var num = this.texture.height/2//(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio; - perp.x /= perpLength; - perp.y /= perpLength; - - perp.x *= num; - perp.y *= num; - - verticies[index] = point.x + perp.x - verticies[index+1] = point.y + perp.y - verticies[index+2] = point.x - perp.x - verticies[index+3] = point.y - perp.y - - lastPoint = point; - } - - PIXI.DisplayObjectContainer.prototype.updateTransform.call( this ); -} - -PIXI.Rope.prototype.setTexture = function(texture) -{ - // stop current texture - this.texture = texture; - this.updateFrame = true; -} - - - - - -/** - * @author Mat Groves http://matgroves.com/ - */ - -/** - * A tiling sprite is a fast way of rendering a tiling image - * - * @class TilingSprite - * @extends DisplayObjectContainer - * @constructor - * @param texture {Texture} the texture of the tiling sprite - * @param width {Number} the width of the tiling sprite - * @param height {Number} the height of the tiling sprite - */ -PIXI.TilingSprite = function(texture, width, height) -{ - PIXI.DisplayObjectContainer.call( this ); - - /** - * The texture that the sprite is using - * - * @property texture - * @type Texture - */ - this.texture = texture; - - /** - * The width of the tiling sprite - * - * @property width - * @type Number - */ - this.width = width; - - /** - * The height of the tiling sprite - * - * @property height - * @type Number - */ - this.height = height; - - /** - * The scaling of the image that is being tiled - * - * @property tileScale - * @type Point - */ - this.tileScale = new PIXI.Point(1,1); - - /** - * The offset position of the image that is being tiled - * - * @property tilePosition - * @type Point - */ - this.tilePosition = new PIXI.Point(0,0); - - this.renderable = true; - - this.blendMode = PIXI.blendModes.NORMAL -} - -// constructor -PIXI.TilingSprite.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); -PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite; - -/** - * Sets the texture of the tiling sprite - * - * @method setTexture - * @param texture {Texture} The PIXI texture that is displayed by the sprite - */ -PIXI.TilingSprite.prototype.setTexture = function(texture) -{ - //TODO SET THE TEXTURES - //TODO VISIBILITY - - // stop current texture - this.texture = texture; - this.updateFrame = true; -} - -/** - * When the texture is updated, this event will fire to update the frame - * - * @method onTextureUpdate - * @param event - * @private - */ -PIXI.TilingSprite.prototype.onTextureUpdate = function(event) -{ - this.updateFrame = true; -} - - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * This is the base class for creating a pixi.js filter. Currently only webGL supports filters. - * If you want to make a custom filter this should be your base class. - * @class AbstractFilter - * @constructor - * @param fragmentSrc - * @param uniforms - */ -PIXI.AbstractFilter = function(fragmentSrc, uniforms) -{ - /** - * An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion. - * For example the blur filter has two passes blurX and blurY. - * @property passes - * @type Array an array of filter objects - * @private - */ - this.passes = [this]; - - - this.dirty = true; - this.padding = 0; - - /** - @property uniforms - @private - */ - this.uniforms = uniforms || {}; - - this.fragmentSrc = fragmentSrc || []; -} - - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * - * The BlurFilter applies a Gaussian blur to an object. - * The strength of the blur can be set for x- and y-axis separately (always relative to the stage). - * - * @class BlurFilter - * @contructor - */ -PIXI.BlurFilter = function() -{ - - this.blurXFilter = new PIXI.BlurXFilter(); - this.blurYFilter = new PIXI.BlurYFilter(); - - this.passes =[this.blurXFilter, this.blurYFilter]; - -} - -/** - * Sets the strength of both the blurX and blurY properties simultaneously - * - * @property blur - * @type Number the strength of the blur - * @default 2 - */ -Object.defineProperty(PIXI.BlurFilter.prototype, 'blur', { - get: function() { - return this.blurXFilter.blur; - }, - set: function(value) { - this.blurXFilter.blur = this.blurYFilter.blur = value; - } -}); - -/** - * Sets the strength of the blurX property simultaneously - * - * @property blurX - * @type Number the strength of the blurX - * @default 2 - */ -Object.defineProperty(PIXI.BlurFilter.prototype, 'blurX', { - get: function() { - return this.blurXFilter.blur; - }, - set: function(value) { - this.blurXFilter.blur = value; - } -}); - -/** - * Sets the strength of the blurX property simultaneously - * - * @property blurY - * @type Number the strength of the blurY - * @default 2 - */ -Object.defineProperty(PIXI.BlurFilter.prototype, 'blurY', { - get: function() { - return this.blurYFilter.blur; - }, - set: function(value) { - this.blurYFilter.blur = value; - } -}); - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - - -PIXI.BlurXFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - blur: {type: '1f', value: 1/512}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float blur;", - "uniform sampler2D uSampler;", - "void main(void) {", - "vec4 sum = vec4(0.0);", - - "sum += texture2D(uSampler, vec2(vTextureCoord.x - 4.0*blur, vTextureCoord.y)) * 0.05;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x - 3.0*blur, vTextureCoord.y)) * 0.09;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x - 2.0*blur, vTextureCoord.y)) * 0.12;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x - blur, vTextureCoord.y)) * 0.15;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * 0.16;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x + blur, vTextureCoord.y)) * 0.15;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x + 2.0*blur, vTextureCoord.y)) * 0.12;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x + 3.0*blur, vTextureCoord.y)) * 0.09;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x + 4.0*blur, vTextureCoord.y)) * 0.05;", - - "gl_FragColor = sum;", - - "}" - ]; -} - -PIXI.BlurXFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.BlurXFilter.prototype.constructor = PIXI.BlurXFilter; - - -Object.defineProperty(PIXI.BlurXFilter.prototype, 'blur', { - get: function() { - return this.uniforms.blur.value / (1/7000); - }, - set: function(value) { - - this.dirty = true; - this.uniforms.blur.value = (1/7000) * value; - } -}); - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - - -PIXI.BlurYFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - blur: {type: '1f', value: 1/512}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float blur;", - "uniform sampler2D uSampler;", - "void main(void) {", - "vec4 sum = vec4(0.0);", - - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - 4.0*blur)) * 0.05;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - 3.0*blur)) * 0.09;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - 2.0*blur)) * 0.12;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - blur)) * 0.15;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * 0.16;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + blur)) * 0.15;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + 2.0*blur)) * 0.12;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + 3.0*blur)) * 0.09;", - "sum += texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + 4.0*blur)) * 0.05;", - - "gl_FragColor = sum;", - - "}" - ]; -} - -PIXI.BlurYFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.BlurYFilter.prototype.constructor = PIXI.BlurYFilter; - -Object.defineProperty(PIXI.BlurYFilter.prototype, 'blur', { - get: function() { - return this.uniforms.blur.value / (1/7000); - }, - set: function(value) { - //this.padding = value; - this.uniforms.blur.value = (1/7000) * value; - } -}); - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * - * The ColorMatrixFilter class lets you apply a 4x4 matrix transformation on the RGBA - * color and alpha values of every pixel on your displayObject to produce a result - * with a new set of RGBA color and alpha values. Its pretty powerful! - * @class ColorMatrixFilter - * @contructor - */ -PIXI.ColorMatrixFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - matrix: {type: 'mat4', value: [1,0,0,0, - 0,1,0,0, - 0,0,1,0, - 0,0,0,1]}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float invert;", - "uniform mat4 matrix;", - "uniform sampler2D uSampler;", - "void main(void) {", - "gl_FragColor = texture2D(uSampler, vTextureCoord) * matrix;", - "gl_FragColor = gl_FragColor * vColor;", - "}" - ]; - -} - -PIXI.ColorMatrixFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.ColorMatrixFilter.prototype.constructor = PIXI.ColorMatrixFilter; - -/** - * Sets the matrix of the color matrix filter - * - * @property matrix - * @type Array and array of 26 numbers - * @default [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] - */ -Object.defineProperty(PIXI.ColorMatrixFilter.prototype, 'matrix', { - get: function() { - return this.uniforms.matrix.value; - }, - set: function(value) { - this.uniforms.matrix.value = value; - } -}); -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - - -PIXI.CrossHatchFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - blur: {type: '1f', value: 1/512}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float blur;", - "uniform sampler2D uSampler;", - "void main(void) {", - - - " float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);", - " ", - " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);", - " ", - " if (lum < 1.00) {", - " if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0) {", - " gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);", - " }", - " }", - " ", - " if (lum < 0.75) {", - " if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0) {", - " gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);", - " }", - " }", - " ", - " if (lum < 0.50) {", - " if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0) {", - " gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);", - " }", - " }", - " ", - " if (lum < 0.3) {", - " if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0) {", - " gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);", - " }", - " }", - "}" - ]; -} - -PIXI.CrossHatchFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.CrossHatchFilter.prototype.constructor = PIXI.BlurYFilter; - -Object.defineProperty(PIXI.CrossHatchFilter.prototype, 'blur', { - get: function() { - return this.uniforms.blur.value / (1/7000); - }, - set: function(value) { - //this.padding = value; - this.uniforms.blur.value = (1/7000) * value; - } -}); - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * - * The DisplacementFilter class uses the pixel values from the specified texture (called the displacement map) to perform a displacement of an object. - * You can use this filter to apply all manor of crazy warping effects - * Currently the r property of the texture is used offset the x and the g propery of the texture is used to offset the y. - * @class DisplacementFilter - * @contructor - * @param texture {Texture} The texture used for the displacemtent map * must be power of 2 texture at the moment - */ -PIXI.DisplacementFilter = function(texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - texture.baseTexture._powerOf2 = true; - - // set the uniforms - //console.log() - this.uniforms = { - displacementMap: {type: 'sampler2D', value:texture}, - scale: {type: '2f', value:{x:30, y:30}}, - offset: {type: '2f', value:{x:0, y:0}}, - mapDimensions: {type: '2f', value:{x:1, y:5112}}, - dimensions: {type: '4fv', value:[0,0,0,0]} - }; - - - if(texture.baseTexture.hasLoaded) - { - this.uniforms.mapDimensions.value.x = texture.width; - this.uniforms.mapDimensions.value.y = texture.height; - } - else - { - this.boundLoadedFunction = this.onTextureLoaded.bind(this); - - texture.baseTexture.on("loaded", this.boundLoadedFunction); - } - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform sampler2D displacementMap;", - "uniform sampler2D uSampler;", - "uniform vec2 scale;", - "uniform vec2 offset;", - "uniform vec4 dimensions;", - "uniform vec2 mapDimensions;",// = vec2(256.0, 256.0);", - // "const vec2 textureDimensions = vec2(750.0, 750.0);", - - "void main(void) {", - "vec2 mapCords = vTextureCoord.xy;", -// "mapCords -= ;", - "mapCords += (dimensions.zw + offset)/ dimensions.xy ;", - "mapCords.y *= -1.0;", - "mapCords.y += 1.0;", - "vec2 matSample = texture2D(displacementMap, mapCords).xy;", - "matSample -= 0.5;", - "matSample *= scale;", - "matSample /= mapDimensions;", - "gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x + matSample.x, vTextureCoord.y + matSample.y));", - "gl_FragColor.rgb = mix( gl_FragColor.rgb, gl_FragColor.rgb, 1.0);", - "vec2 cord = vTextureCoord;", - - //"gl_FragColor = texture2D(displacementMap, cord);", - "gl_FragColor = gl_FragColor * vColor;", - - "}" - ]; - -} - -PIXI.DisplacementFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.DisplacementFilter.prototype.constructor = PIXI.DisplacementFilter; - -PIXI.DisplacementFilter.prototype.onTextureLoaded = function() -{ - - this.uniforms.mapDimensions.value.x = this.uniforms.displacementMap.value.width; - this.uniforms.mapDimensions.value.y = this.uniforms.displacementMap.value.height; - - this.uniforms.displacementMap.value.baseTexture.off("loaded", this.boundLoadedFunction) - -} - -/** - * The texture used for the displacemtent map * must be power of 2 texture at the moment - * - * @property map - * @type Texture - */ -Object.defineProperty(PIXI.DisplacementFilter.prototype, 'map', { - get: function() { - return this.uniforms.displacementMap.value; - }, - set: function(value) { - this.uniforms.displacementMap.value = value; - } -}); - -/** - * The multiplier used to scale the displacement result from the map calculation. - * - * @property scale - * @type Point - */ -Object.defineProperty(PIXI.DisplacementFilter.prototype, 'scale', { - get: function() { - return this.uniforms.scale.value; - }, - set: function(value) { - this.uniforms.scale.value = value; - } -}); - -/** - * The offset used to move the displacement map. - * - * @property offset - * @type Point - */ -Object.defineProperty(PIXI.DisplacementFilter.prototype, 'offset', { - get: function() { - return this.uniforms.offset.value; - }, - set: function(value) { - this.uniforms.offset.value = value; - } -}); -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/fun/dotscreen.js - */ - -/** - * - * This filter applies a pixlate effect making display objects appear "blocky" - * @class PixelateFilter - * @contructor - */ -PIXI.DotScreenFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - scale: {type: '1f', value:1}, - angle: {type: '1f', value:5}, - dimensions: {type: '4fv', value:[0,0,0,0]} - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform vec4 dimensions;", - "uniform sampler2D uSampler;", - - "uniform float angle;", - "uniform float scale;", - - "float pattern() {", - "float s = sin(angle), c = cos(angle);", - "vec2 tex = vTextureCoord * dimensions.xy;", - "vec2 point = vec2(", - "c * tex.x - s * tex.y,", - "s * tex.x + c * tex.y", - ") * scale;", - "return (sin(point.x) * sin(point.y)) * 4.0;", - "}", - - "void main() {", - "vec4 color = texture2D(uSampler, vTextureCoord);", - "float average = (color.r + color.g + color.b) / 3.0;", - "gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);", - "}", - ]; -} - -PIXI.DotScreenFilter.prototype = Object.create( PIXI.DotScreenFilter.prototype ); -PIXI.DotScreenFilter.prototype.constructor = PIXI.DotScreenFilter; - -/** - * - * This describes the the scale - * @property scale - * @type Number - */ -Object.defineProperty(PIXI.DotScreenFilter.prototype, 'scale', { - get: function() { - return this.uniforms.scale.value; - }, - set: function(value) { - this.dirty = true; - this.uniforms.scale.value = value; - } -}); - -/** - * - * This radius describes angle - * @property angle - * @type Number - */ -Object.defineProperty(PIXI.DotScreenFilter.prototype, 'angle', { - get: function() { - return this.uniforms.angle.value; - }, - set: function(value) { - this.dirty = true; - this.uniforms.angle.value = value; - } -}); -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - - -PIXI.FilterBlock = function() -{ - this.visible = true; - this.renderable = true; -} -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * - * This inverts your displayObjects colors. - * @class InvertFilter - * @contructor - */ -PIXI.InvertFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - invert: {type: '1f', value: 1}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float invert;", - "uniform sampler2D uSampler;", - "void main(void) {", - "gl_FragColor = texture2D(uSampler, vTextureCoord);", - "gl_FragColor.rgb = mix( (vec3(1)-gl_FragColor.rgb) * gl_FragColor.a, gl_FragColor.rgb, 1.0 - invert);", - //"gl_FragColor.rgb = gl_FragColor.rgb * gl_FragColor.a;", - "gl_FragColor = gl_FragColor * vColor;", - "}" - ]; - -} - -PIXI.InvertFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.InvertFilter.prototype.constructor = PIXI.InvertFilter; - -/** -The strength of the invert. 1 will fully invert the colors, 0 will make the object its normal color -@property invert -*/ -Object.defineProperty(PIXI.InvertFilter.prototype, 'invert', { - get: function() { - return this.uniforms.invert.value; - }, - set: function(value) { - this.uniforms.invert.value = value; - } -}); -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * - * This filter applies a pixlate effect making display objects appear "blocky" - * @class PixelateFilter - * @contructor - */ -PIXI.PixelateFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - invert: {type: '1f', value: 0}, - dimensions: {type: '4fv', value:new Float32Array([10000, 100, 10, 10])}, - pixelSize: {type: '2f', value:{x:10, y:10}}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform vec2 testDim;", - "uniform vec4 dimensions;", - "uniform vec2 pixelSize;", - "uniform sampler2D uSampler;", - "void main(void) {", - "vec2 coord = vTextureCoord;", - - "vec2 size = dimensions.xy/pixelSize;", - - "vec2 color = floor( ( vTextureCoord * size ) ) / size + pixelSize/dimensions.xy * 0.5;", - "gl_FragColor = texture2D(uSampler, color);", - "}" - ]; - - -} - -PIXI.PixelateFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.PixelateFilter.prototype.constructor = PIXI.PixelateFilter; - -/** - * - * This a point that describes the size of the blocs. x is the width of the block and y is the the height - * @property size - * @type Point - */ -Object.defineProperty(PIXI.PixelateFilter.prototype, 'size', { - get: function() { - return this.uniforms.pixelSize.value; - }, - set: function(value) { - this.dirty = true; - this.uniforms.pixelSize.value = value; - } -}); -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - - -PIXI.RGBSplitFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - red: {type: '2f', value: {x:20, y:20}}, - green: {type: '2f', value: {x:-20, y:20}}, - blue: {type: '2f', value: {x:20, y:-20}}, - dimensions: {type: '4fv', value:[0,0,0,0]} - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform vec2 red;", - "uniform vec2 green;", - "uniform vec2 blue;", - "uniform vec4 dimensions;", - "uniform sampler2D uSampler;", - "void main(void) {", - "gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/dimensions.xy).r;", - "gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/dimensions.xy).g;", - "gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/dimensions.xy).b;", - "gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;", - "}" - ]; -} - -PIXI.RGBSplitFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.RGBSplitFilter.prototype.constructor = PIXI.RGBSplitFilter; - -Object.defineProperty(PIXI.RGBSplitFilter.prototype, 'angle', { - get: function() { - return this.uniforms.blur.value / (1/7000); - }, - set: function(value) { - //this.padding = value; - this.uniforms.blur.value = (1/7000) * value; - } -}); - -/** -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * - * This applies a sepia effect to your displayObjects. - * @class SepiaFilter - * @contructor - */ -PIXI.SepiaFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - sepia: {type: '1f', value: 1}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float sepia;", - "uniform sampler2D uSampler;", - - "const mat3 sepiaMatrix = mat3(0.3588, 0.7044, 0.1368, 0.2990, 0.5870, 0.1140, 0.2392, 0.4696, 0.0912);", - "void main(void) {", - "gl_FragColor = texture2D(uSampler, vTextureCoord);", - "gl_FragColor.rgb = mix( gl_FragColor.rgb, gl_FragColor.rgb * sepiaMatrix, sepia);", - "gl_FragColor = gl_FragColor * vColor;", - "}" - ]; - -} - -PIXI.SepiaFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.SepiaFilter.prototype.constructor = PIXI.SepiaFilter; - -/** -The strength of the sepia. 1 will apply the full sepia effect, 0 will make the object its normal color -@property sepia -*/ -Object.defineProperty(PIXI.SepiaFilter.prototype, 'sepia', { - get: function() { - return this.uniforms.sepia.value; - }, - set: function(value) { - this.uniforms.sepia.value = value; - } -}); - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - - -PIXI.SmartBlurFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - blur: {type: '1f', value: 1/512}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "uniform sampler2D uSampler;", - // "uniform vec2 delta;", - "const vec2 delta = vec2(1.0/10.0, 0.0);", - // "uniform float darkness;", - - "float random(vec3 scale, float seed) {", - "return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);", - "}", - - - "void main(void) {", - - "vec4 color = vec4(0.0);", - "float total = 0.0;", - - "float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);", - - "for (float t = -30.0; t <= 30.0; t++) {", - "float percent = (t + offset - 0.5) / 30.0;", - "float weight = 1.0 - abs(percent);", - "vec4 sample = texture2D(uSampler, vTextureCoord + delta * percent);", - "sample.rgb *= sample.a;", - "color += sample * weight;", - "total += weight;", - "}", - - "gl_FragColor = color / total;", - "gl_FragColor.rgb /= gl_FragColor.a + 0.00001;", - // "gl_FragColor.rgb *= darkness;", - "}" - ]; -} - -PIXI.SmartBlurFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.SmartBlurFilter.prototype.constructor = PIXI.SmartBlurFilter; - -Object.defineProperty(PIXI.SmartBlurFilter.prototype, 'blur', { - get: function() { - return this.uniforms.blur.value; - }, - set: function(value) { - this.uniforms.blur.value = value; - } -}); - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * - * This filter applies a pixlate effect making display objects appear "blocky" - * @class PixelateFilter - * @contructor - */ -PIXI.TwistFilter = function() -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - // set the uniforms - this.uniforms = { - radius: {type: '1f', value:0.5}, - angle: {type: '1f', value:5}, - offset: {type: '2f', value:{x:0.5, y:0.5}}, - }; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform vec4 dimensions;", - "uniform sampler2D uSampler;", - - "uniform float radius;", - "uniform float angle;", - "uniform vec2 offset;", - - "void main(void) {", - "vec2 coord = vTextureCoord - offset;", - "float distance = length(coord);", - - "if (distance < radius){", - - "float ratio = (radius - distance) / radius;", - "float angleMod = ratio * ratio * angle;", - "float s = sin(angleMod);", - "float c = cos(angleMod);", - "coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);", - - "}", - - "gl_FragColor = texture2D(uSampler, coord+offset);", - "}" - ]; -} - -PIXI.TwistFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.TwistFilter.prototype.constructor = PIXI.TwistFilter; - -/** - * - * This point describes the the offset of the twist - * @property size - * @type Point - */ -Object.defineProperty(PIXI.TwistFilter.prototype, 'offset', { - get: function() { - return this.uniforms.offset.value; - }, - set: function(value) { - this.dirty = true; - this.uniforms.offset.value = value; - } -}); - -/** - * - * This radius describes size of the twist - * @property size - * @type Number - */ -Object.defineProperty(PIXI.TwistFilter.prototype, 'radius', { - get: function() { - return this.uniforms.radius.value; - }, - set: function(value) { - this.dirty = true; - this.uniforms.radius.value = value; - } -}); - -/** - * - * This radius describes angle of the twist - * @property angle - * @type Number - */ -Object.defineProperty(PIXI.TwistFilter.prototype, 'angle', { - get: function() { - return this.uniforms.angle.value; - }, - set: function(value) { - this.dirty = true; - this.uniforms.angle.value = value; - } -}); -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * The Graphics class contains a set of methods that you can use to create primitive shapes and lines. - * It is important to know that with the webGL renderer only simple polys can be filled at this stage - * Complex polys will not be filled. Heres an example of a complex poly: http://www.goodboydigital.com/wp-content/uploads/2013/06/complexPolygon.png - * - * @class Graphics - * @extends DisplayObjectContainer - * @constructor - */ -PIXI.Graphics = function() -{ - PIXI.DisplayObjectContainer.call( this ); - - this.renderable = true; - - /** - * The alpha of the fill of this graphics object - * - * @property fillAlpha - * @type Number - */ - this.fillAlpha = 1; - - /** - * The width of any lines drawn - * - * @property lineWidth - * @type Number - */ - this.lineWidth = 0; - - /** - * The color of any lines drawn - * - * @property lineColor - * @type String - */ - this.lineColor = "black"; - - /** - * Graphics data - * - * @property graphicsData - * @type Array - * @private - */ - this.graphicsData = []; - - /** - * Current path - * - * @property currentPath - * @type Object - * @private - */ - this.currentPath = {points:[]}; -} - -// constructor -PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype ); -PIXI.Graphics.prototype.constructor = PIXI.Graphics; - -/** - * Specifies a line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method. - * - * @method lineStyle - * @param lineWidth {Number} width of the line to draw, will update the object's stored style - * @param color {Number} color of the line to draw, will update the object's stored style - * @param alpha {Number} alpha of the line to draw, will update the object's stored style - */ -PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha) -{ - if(this.currentPath.points.length == 0)this.graphicsData.pop(); - - this.lineWidth = lineWidth || 0; - this.lineColor = color || 0; - this.lineAlpha = (alpha == undefined) ? 1 : alpha; - - this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha, - fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY}; - - this.graphicsData.push(this.currentPath); -} - -/** - * Moves the current drawing position to (x, y). - * - * @method moveTo - * @param x {Number} the X coord to move to - * @param y {Number} the Y coord to move to - */ -PIXI.Graphics.prototype.moveTo = function(x, y) -{ - if(this.currentPath.points.length == 0)this.graphicsData.pop(); - - this.currentPath = this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha, - fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, points:[], type:PIXI.Graphics.POLY}; - - this.currentPath.points.push(x, y); - - this.graphicsData.push(this.currentPath); -} - -/** - * Draws a line using the current line style from the current drawing position to (x, y); - * the current drawing position is then set to (x, y). - * - * @method lineTo - * @param x {Number} the X coord to draw to - * @param y {Number} the Y coord to draw to - */ -PIXI.Graphics.prototype.lineTo = function(x, y) -{ - this.currentPath.points.push(x, y); - this.dirty = true; -} - -/** - * Specifies a simple one-color fill that subsequent calls to other Graphics methods - * (such as lineTo() or drawCircle()) use when drawing. - * - * @method beginFill - * @param color {uint} the color of the fill - * @param alpha {Number} the alpha - */ -PIXI.Graphics.prototype.beginFill = function(color, alpha) -{ - this.filling = true; - this.fillColor = color || 0; - this.fillAlpha = (alpha == undefined) ? 1 : alpha; -} - -/** - * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. - * - * @method endFill - */ -PIXI.Graphics.prototype.endFill = function() -{ - this.filling = false; - this.fillColor = null; - this.fillAlpha = 1; -} - -/** - * @method drawRect - * - * @param x {Number} The X coord of the top-left of the rectangle - * @param y {Number} The Y coord of the top-left of the rectangle - * @param width {Number} The width of the rectangle - * @param height {Number} The height of the rectangle - */ -PIXI.Graphics.prototype.drawRect = function( x, y, width, height ) -{ - if(this.currentPath.points.length == 0)this.graphicsData.pop(); - - this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha, - fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, - points:[x, y, width, height], type:PIXI.Graphics.RECT}; - - this.graphicsData.push(this.currentPath); - this.dirty = true; -} - -/** - * Draws a circle. - * - * @method drawCircle - * @param x {Number} The X coord of the center of the circle - * @param y {Number} The Y coord of the center of the circle - * @param radius {Number} The radius of the circle - */ -PIXI.Graphics.prototype.drawCircle = function( x, y, radius) -{ - if(this.currentPath.points.length == 0)this.graphicsData.pop(); - - this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha, - fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, - points:[x, y, radius, radius], type:PIXI.Graphics.CIRC}; - - this.graphicsData.push(this.currentPath); - this.dirty = true; -} - -/** - * Draws an elipse. - * - * @method drawElipse - * @param x {Number} - * @param y {Number} - * @param width {Number} - * @param height {Number} - */ -PIXI.Graphics.prototype.drawElipse = function( x, y, width, height) -{ - if(this.currentPath.points.length == 0)this.graphicsData.pop(); - - this.currentPath = {lineWidth:this.lineWidth, lineColor:this.lineColor, lineAlpha:this.lineAlpha, - fillColor:this.fillColor, fillAlpha:this.fillAlpha, fill:this.filling, - points:[x, y, width, height], type:PIXI.Graphics.ELIP}; - - this.graphicsData.push(this.currentPath); - this.dirty = true; -} - -/** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * - * @method clear - */ -PIXI.Graphics.prototype.clear = function() -{ - this.lineWidth = 0; - this.filling = false; - - this.dirty = true; - this.clearDirty = true; - this.graphicsData = []; - - this.bounds = null//new PIXI.Rectangle(); -} - - -PIXI.Graphics.prototype.updateFilterBounds = function() -{ - if(!this.bounds) - { - var minX = Infinity; - var maxX = -Infinity; - - var minY = Infinity; - var maxY = -Infinity; - - var points, x, y; - - for (var i = 0; i < this.graphicsData.length; i++) { - - - var data = this.graphicsData[i]; - var type = data.type; - var lineWidth = data.lineWidth; - - points = data.points; - - if(type === PIXI.Graphics.RECT) - { - x = points.x - lineWidth/2; - y = points.y - lineWidth/2; - var width = points.width + lineWidth; - var height = points.height + lineWidth; - - minX = x < minX ? x : minX; - maxX = x + width > maxX ? x + width : maxX; - - minY = y < minY ? x : minY; - maxY = y + height > maxY ? y + height : maxY; - } - else if(type === PIXI.Graphics.CIRC || type === PIXI.Graphics.ELIP) - { - x = points.x; - y = points.y; - var radius = points.radius + lineWidth/2; - - minX = x - radius < minX ? x - radius : minX; - maxX = x + radius > maxX ? x + radius : maxX; - - minY = y - radius < minY ? y - radius : minY; - maxY = y + radius > maxY ? y + radius : maxY; - } - else - { - // POLY - for (var j = 0; j < points.length; j+=2) - { - - x = points[j]; - y = points[j+1]; - - minX = x-lineWidth < minX ? x-lineWidth : minX; - maxX = x+lineWidth > maxX ? x+lineWidth : maxX; - - minY = y-lineWidth < minY ? y-lineWidth : minY; - maxY = y+lineWidth > maxY ? y+lineWidth : maxY; - }; - } - - }; - - this.bounds = new PIXI.Rectangle(minX, minY, maxX - minX, maxY - minY); - - } - -// console.log(this.bounds); -} - -// SOME TYPES: -PIXI.Graphics.POLY = 0; -PIXI.Graphics.RECT = 1; -PIXI.Graphics.CIRC = 2; -PIXI.Graphics.ELIP = 3; - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * A set of functions used by the canvas renderer to draw the primitive graphics data - * - * @class CanvasGraphics - */ -PIXI.CanvasGraphics = function() -{ - -} - - -/* - * Renders the graphics object - * - * @static - * @private - * @method renderGraphics - * @param graphics {Graphics} - * @param context {Context2D} - */ -PIXI.CanvasGraphics.renderGraphics = function(graphics, context) -{ - var worldAlpha = graphics.worldAlpha; - - for (var i=0; i < graphics.graphicsData.length; i++) - { - var data = graphics.graphicsData[i]; - var points = data.points; - - context.strokeStyle = color = '#' + ('00000' + ( data.lineColor | 0).toString(16)).substr(-6); - - context.lineWidth = data.lineWidth; - - if(data.type == PIXI.Graphics.POLY) - { - context.beginPath(); - - context.moveTo(points[0], points[1]); - - for (var j=1; j < points.length/2; j++) - { - context.lineTo(points[j * 2], points[j * 2 + 1]); - } - - // if the first and last point are the same close the path - much neater :) - if(points[0] == points[points.length-2] && points[1] == points[points.length-1]) - { - context.closePath(); - } - - if(data.fill) - { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - if(data.lineWidth) - { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.stroke(); - } - } - else if(data.type == PIXI.Graphics.RECT) - { - - if(data.fillColor || data.fillColor === 0) - { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6); - context.fillRect(points[0], points[1], points[2], points[3]); - - } - if(data.lineWidth) - { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.strokeRect(points[0], points[1], points[2], points[3]); - } - - } - else if(data.type == PIXI.Graphics.CIRC) - { - // TODO - need to be Undefined! - context.beginPath(); - context.arc(points[0], points[1], points[2],0,2*Math.PI); - context.closePath(); - - if(data.fill) - { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - if(data.lineWidth) - { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.stroke(); - } - } - else if(data.type == PIXI.Graphics.ELIP) - { - - // elipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - - var elipseData = data.points; - - var w = elipseData[2] * 2; - var h = elipseData[3] * 2; - - var x = elipseData[0] - w/2; - var y = elipseData[1] - h/2; - - context.beginPath(); - - var kappa = .5522848, - ox = (w / 2) * kappa, // control point offset horizontal - oy = (h / 2) * kappa, // control point offset vertical - xe = x + w, // x-end - ye = y + h, // y-end - xm = x + w / 2, // x-middle - ym = y + h / 2; // y-middle - - context.moveTo(x, ym); - context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - - context.closePath(); - - if(data.fill) - { - context.globalAlpha = data.fillAlpha * worldAlpha; - context.fillStyle = color = '#' + ('00000' + ( data.fillColor | 0).toString(16)).substr(-6); - context.fill(); - } - if(data.lineWidth) - { - context.globalAlpha = data.lineAlpha * worldAlpha; - context.stroke(); - } - } - - }; -} - -/* - * Renders a graphics mask - * - * @static - * @private - * @method renderGraphicsMask - * @param graphics {Graphics} - * @param context {Context2D} - */ -PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context) -{ - var worldAlpha = graphics.worldAlpha; - - var len = graphics.graphicsData.length; - if(len === 0)return; - - if(len > 1) - { - len = 1; - console.log("Pixi.js warning: masks in canvas can only mask using the first path in the graphics object") - } - - for (var i=0; i < 1; i++) - { - var data = graphics.graphicsData[i]; - var points = data.points; - - if(data.type == PIXI.Graphics.POLY) - { - context.beginPath(); - context.moveTo(points[0], points[1]); - - for (var j=1; j < points.length/2; j++) - { - context.lineTo(points[j * 2], points[j * 2 + 1]); - } - - // if the first and last point are the same close the path - much neater :) - if(points[0] == points[points.length-2] && points[1] == points[points.length-1]) - { - context.closePath(); - } - - } - else if(data.type == PIXI.Graphics.RECT) - { - context.beginPath(); - context.rect(points[0], points[1], points[2], points[3]); - context.closePath(); - } - else if(data.type == PIXI.Graphics.CIRC) - { - // TODO - need to be Undefined! - context.beginPath(); - context.arc(points[0], points[1], points[2],0,2*Math.PI); - context.closePath(); - } - else if(data.type == PIXI.Graphics.ELIP) - { - - // elipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas - var elipseData = data.points; - - var w = elipseData[2] * 2; - var h = elipseData[3] * 2; - - var x = elipseData[0] - w/2; - var y = elipseData[1] - h/2; - - context.beginPath(); - - var kappa = .5522848, - ox = (w / 2) * kappa, // control point offset horizontal - oy = (h / 2) * kappa, // control point offset vertical - xe = x + w, // x-end - ye = y + h, // y-end - xm = x + w / 2, // x-middle - ym = y + h / 2; // y-middle - - context.moveTo(x, ym); - context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - context.closePath(); - } - - - }; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -/** - * the CanvasRenderer draws the stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL. - * Dont forget to add the view to your DOM or you will not see anything :) - * - * @class CanvasRenderer - * @constructor - * @param width=0 {Number} the width of the canvas view - * @param height=0 {Number} the height of the canvas view - * @param view {Canvas} the canvas to use as a view, optional - * @param transparent=false {Boolean} the transparency of the render view, default false - */ -PIXI.CanvasRenderer = function(width, height, view, transparent) -{ - this.transparent = transparent; - - /** - * The width of the canvas view - * - * @property width - * @type Number - * @default 800 - */ - this.width = width || 800; - - /** - * The height of the canvas view - * - * @property height - * @type Number - * @default 600 - */ - this.height = height || 600; - - /** - * The canvas element that the everything is drawn to - * - * @property view - * @type Canvas - */ - this.view = view || document.createElement( 'canvas' ); - - /** - * The canvas context that the everything is drawn to - * @property context - * @type Canvas 2d Context - */ - this.context = this.view.getContext("2d"); - - this.refresh = true; - // hack to enable some hardware acceleration! - //this.view.style["transform"] = "translatez(0)"; - - this.view.width = this.width; - this.view.height = this.height; - this.count = 0; -} - -// constructor -PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer; - -/** - * Renders the stage to its canvas view - * - * @method render - * @param stage {Stage} the Stage element to be rendered - */ -PIXI.CanvasRenderer.prototype.render = function(stage) -{ - - //stage.__childrenAdded = []; - //stage.__childrenRemoved = []; - - // update textures if need be - PIXI.texturesToUpdate = []; - PIXI.texturesToDestroy = []; - - PIXI.visibleCount++; - stage.updateTransform(); - - // update the background color - if(this.view.style.backgroundColor!=stage.backgroundColorString && !this.transparent)this.view.style.backgroundColor = stage.backgroundColorString; - - this.context.setTransform(1,0,0,1,0,0); - this.context.clearRect(0, 0, this.width, this.height) - this.renderDisplayObject(stage); - //as - - // run interaction! - if(stage.interactive) - { - //need to add some events! - if(!stage._interactiveEventsAdded) - { - stage._interactiveEventsAdded = true; - stage.interactionManager.setTarget(this); - } - } - - // remove frame updates.. - if(PIXI.Texture.frameUpdates.length > 0) - { - PIXI.Texture.frameUpdates = []; - } - - -} - -/** - * resizes the canvas view to the specified width and height - * - * @method resize - * @param width {Number} the new width of the canvas view - * @param height {Number} the new height of the canvas view - */ -PIXI.CanvasRenderer.prototype.resize = function(width, height) -{ - this.width = width; - this.height = height; - - this.view.width = width; - this.view.height = height; -} - -/** - * Renders a display object - * - * @method renderDisplayObject - * @param displayObject {DisplayObject} The displayObject to render - * @private - */ -PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject) -{ - // no loger recurrsive! - var transform; - var context = this.context; - - context.globalCompositeOperation = 'source-over'; - - // one the display object hits this. we can break the loop - var testObject = displayObject.last._iNext; - displayObject = displayObject.first; - - do - { - transform = displayObject.worldTransform; - - if(!displayObject.visible) - { - displayObject = displayObject.last._iNext; - continue; - } - - if(!displayObject.renderable) - { - displayObject = displayObject._iNext; - continue; - } - - if(displayObject instanceof PIXI.Sprite) - { - - var frame = displayObject.texture.frame; - - if(frame && frame.width && frame.height) - { - context.globalAlpha = displayObject.worldAlpha; - - context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]); - - context.drawImage(displayObject.texture.baseTexture.source, - frame.x, - frame.y, - frame.width, - frame.height, - (displayObject.anchor.x) * -frame.width, - (displayObject.anchor.y) * -frame.height, - frame.width, - frame.height); - } - } - else if(displayObject instanceof PIXI.Strip) - { - context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]) - this.renderStrip(displayObject); - } - else if(displayObject instanceof PIXI.TilingSprite) - { - context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]) - this.renderTilingSprite(displayObject); - } - else if(displayObject instanceof PIXI.CustomRenderable) - { - context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]); - displayObject.renderCanvas(this); - } - else if(displayObject instanceof PIXI.Graphics) - { - context.setTransform(transform[0], transform[3], transform[1], transform[4], transform[2], transform[5]) - PIXI.CanvasGraphics.renderGraphics(displayObject, context); - } - else if(displayObject instanceof PIXI.FilterBlock) - { - if(displayObject.data instanceof PIXI.Graphics) - { - var mask = displayObject.data; - - if(displayObject.open) - { - context.save(); - - var cacheAlpha = mask.alpha; - var maskTransform = mask.worldTransform; - - context.setTransform(maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5]) - - mask.worldAlpha = 0.5; - - context.worldAlpha = 0; - - PIXI.CanvasGraphics.renderGraphicsMask(mask, context); - context.clip(); - - mask.worldAlpha = cacheAlpha; - } - else - { - context.restore(); - } - } - else - { - // only masks supported right now! - } - } - // count++ - displayObject = displayObject._iNext; - - - } - while(displayObject != testObject) - - -} - -/** - * Renders a flat strip - * - * @method renderStripFlat - * @param strip {Strip} The Strip to render - * @private - */ -PIXI.CanvasRenderer.prototype.renderStripFlat = function(strip) -{ - var context = this.context; - var verticies = strip.verticies; - var uvs = strip.uvs; - - var length = verticies.length/2; - this.count++; - - context.beginPath(); - for (var i=1; i < length-2; i++) - { - - // draw some triangles! - var index = i*2; - - var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4]; - var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5]; - - context.moveTo(x0, y0); - context.lineTo(x1, y1); - context.lineTo(x2, y2); - - }; - - context.fillStyle = "#FF0000"; - context.fill(); - context.closePath(); -} - -/** - * Renders a tiling sprite - * - * @method renderTilingSprite - * @param sprite {TilingSprite} The tilingsprite to render - * @private - */ -PIXI.CanvasRenderer.prototype.renderTilingSprite = function(sprite) -{ - var context = this.context; - - context.globalAlpha = sprite.worldAlpha; - - if(!sprite.__tilePattern) sprite.__tilePattern = context.createPattern(sprite.texture.baseTexture.source, "repeat"); - - context.beginPath(); - - var tilePosition = sprite.tilePosition; - var tileScale = sprite.tileScale; - - // offset - context.scale(tileScale.x,tileScale.y); - context.translate(tilePosition.x, tilePosition.y); - - context.fillStyle = sprite.__tilePattern; - context.fillRect(-tilePosition.x,-tilePosition.y,sprite.width / tileScale.x, sprite.height / tileScale.y); - - context.scale(1/tileScale.x, 1/tileScale.y); - context.translate(-tilePosition.x, -tilePosition.y); - - context.closePath(); -} - -/** - * Renders a strip - * - * @method renderStrip - * @param strip {Strip} The Strip to render - * @private - */ -PIXI.CanvasRenderer.prototype.renderStrip = function(strip) -{ - var context = this.context; - - // draw triangles!! - var verticies = strip.verticies; - var uvs = strip.uvs; - - var length = verticies.length/2; - this.count++; - for (var i=1; i < length-2; i++) - { - - // draw some triangles! - var index = i*2; - - var x0 = verticies[index], x1 = verticies[index+2], x2 = verticies[index+4]; - var y0 = verticies[index+1], y1 = verticies[index+3], y2 = verticies[index+5]; - - var u0 = uvs[index] * strip.texture.width, u1 = uvs[index+2] * strip.texture.width, u2 = uvs[index+4]* strip.texture.width; - var v0 = uvs[index+1]* strip.texture.height, v1 = uvs[index+3] * strip.texture.height, v2 = uvs[index+5]* strip.texture.height; - - - context.save(); - context.beginPath(); - context.moveTo(x0, y0); - context.lineTo(x1, y1); - context.lineTo(x2, y2); - context.closePath(); - - context.clip(); - - - // Compute matrix transform - var delta = u0*v1 + v0*u2 + u1*v2 - v1*u2 - v0*u1 - u0*v2; - var delta_a = x0*v1 + v0*x2 + x1*v2 - v1*x2 - v0*x1 - x0*v2; - var delta_b = u0*x1 + x0*u2 + u1*x2 - x1*u2 - x0*u1 - u0*x2; - var delta_c = u0*v1*x2 + v0*x1*u2 + x0*u1*v2 - x0*v1*u2 - v0*u1*x2 - u0*x1*v2; - var delta_d = y0*v1 + v0*y2 + y1*v2 - v1*y2 - v0*y1 - y0*v2; - var delta_e = u0*y1 + y0*u2 + u1*y2 - y1*u2 - y0*u1 - u0*y2; - var delta_f = u0*v1*y2 + v0*y1*u2 + y0*u1*v2 - y0*v1*u2 - v0*u1*y2 - u0*y1*v2; - - - - - context.transform(delta_a/delta, delta_d/delta, - delta_b/delta, delta_e/delta, - delta_c/delta, delta_f/delta); - - context.drawImage(strip.texture.baseTexture.source, 0, 0); - context.restore(); - }; - -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - * @author Richard Davey http://www.photonstorm.com @photonstorm - */ - -/** -* @class PIXI.PixiShader -* @constructor -*/ -PIXI.PixiShader = function() -{ - /** - * @property {any} program - The WebGL program. - */ - this.program; - - /** - * @property {array} fragmentSrc - The fragment shader. - */ - this.fragmentSrc = [ - "precision lowp float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform sampler2D uSampler;", - "void main(void) {", - "gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor;", - "}" - ]; - - /** - * @property {number} textureCount - A local texture counter for multi-texture shaders. - */ - this.textureCount = 0; - -} - -/** -* @method PIXI.PixiShader#init -*/ -PIXI.PixiShader.prototype.init = function() -{ - var program = PIXI.compileProgram(this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc) - - var gl = PIXI.gl; - - gl.useProgram(program); - - // get and store the uniforms for the shader - this.uSampler = gl.getUniformLocation(program, "uSampler"); - this.projectionVector = gl.getUniformLocation(program, "projectionVector"); - this.offsetVector = gl.getUniformLocation(program, "offsetVector"); - // this.dimensions = gl.getUniformLocation(program, "dimensions"); - - // get and store the attributes - this.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition"); - this.colorAttribute = gl.getAttribLocation(program, "aColor"); - this.aTextureCoord = gl.getAttribLocation(program, "aTextureCoord"); - - // add those custom shaders! - for (var key in this.uniforms) - { - // get the uniform locations.. - this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key); - } - - this.program = program; -} - -/** -* Updates the shader uniform values. -* Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/ -* http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf -* -* @method PIXI.PixiShader#syncUniforms -*/ -PIXI.PixiShader.prototype.syncUniforms = function() -{ - this.textureCount = 1; - - var gl = PIXI.gl; - - for (var key in this.uniforms) - { - var type = this.uniforms[key].type; - var transpose = false; - - if (this.uniforms[key].transpose) - { - transpose = this.uniforms[key].transpose; - } - - if (type == "1f") - { - // void uniform1f(WebGLUniformLocation? location, GLfloat x); - gl.uniform1f(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "1fv") - { - // void uniform1fv(WebGLUniformLocation? location, Float32Array v); - // void uniform1fv(WebGLUniformLocation? location, sequence v); - gl.uniform1fv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "1i") - { - // void uniform1i(WebGLUniformLocation? location, GLint x); - gl.uniform1i(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "1iv") - { - // void uniform1iv(WebGLUniformLocation? location, Int32Array v); - // void uniform1iv(WebGLUniformLocation? location, sequence v); - gl.uniform1i(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "2f") - { - // void uniform2f(WebGLUniformLocation? location, GLfloat x, GLfloat y); - gl.uniform2f(this.uniforms[key].uniformLocation, this.uniforms[key].value.x, this.uniforms[key].value.y); - } - else if (type == "2fv") - { - // void uniform2fv(WebGLUniformLocation? location, Float32Array v); - // void uniform2fv(WebGLUniformLocation? location, sequence v); - gl.uniform2fv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "2i") - { - // void uniform2i(WebGLUniformLocation? location, GLint x, GLint y); - gl.uniform2i(this.uniforms[key].uniformLocation, this.uniforms[key].value.x, this.uniforms[key].value.y); - } - else if (type == "2iv") - { - // void uniform2iv(WebGLUniformLocation? location, Int32Array v); - // void uniform2iv(WebGLUniformLocation? location, sequence v); - gl.uniform2iv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "3f") - { - // void uniform3f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z); - gl.uniform3f(this.uniforms[key].uniformLocation, this.uniforms[key].value.x, this.uniforms[key].value.y, this.uniforms[key].value.z); - } - else if (type == "3fv") - { - // void uniform3fv(WebGLUniformLocation? location, Float32Array v); - // void uniform3fv(WebGLUniformLocation? location, sequence v); - gl.uniform3fv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "3i") - { - // void uniform3i(WebGLUniformLocation? location, GLint x, GLint y, GLint z); - gl.uniform3i(this.uniforms[key].uniformLocation, this.uniforms[key].value.x, this.uniforms[key].value.y, this.uniforms[key].value.z); - } - else if (type == "3iv") - { - // void uniform3iv(WebGLUniformLocation? location, Int32Array v); - // void uniform3iv(WebGLUniformLocation? location, sequence v); - gl.uniform3iv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "4f") - { - // void uniform4f(WebGLUniformLocation? location, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - gl.uniform4f(this.uniforms[key].uniformLocation, this.uniforms[key].value.x, this.uniforms[key].value.y, this.uniforms[key].value.z, this.uniforms[key].value.w); - } - else if (type == "4fv") - { - // void uniform4fv(WebGLUniformLocation? location, Float32Array v); - // void uniform4fv(WebGLUniformLocation? location, sequence v); - gl.uniform4fv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "4i") - { - // void uniform4i(WebGLUniformLocation? location, GLint x, GLint y, GLint z, GLint w); - gl.uniform4i(this.uniforms[key].uniformLocation, this.uniforms[key].value.x, this.uniforms[key].value.y, this.uniforms[key].value.z, this.uniforms[key].value.w); - } - else if (type == "4iv") - { - // void uniform4iv(WebGLUniformLocation? location, Int32Array v); - // void uniform4iv(WebGLUniformLocation? location, sequence v); - gl.uniform4iv(this.uniforms[key].uniformLocation, this.uniforms[key].value); - } - else if (type == "mat2") - { - // void uniformMatrix2fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array value); - // void uniformMatrix2fv(WebGLUniformLocation? location, GLboolean transpose, sequence value); - gl.uniformMatrix2fv(this.uniforms[key].uniformLocation, transpose, this.uniforms[key].value); - } - else if (type == "mat3") - { - // void uniformMatrix3fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array value); - // void uniformMatrix3fv(WebGLUniformLocation? location, GLboolean transpose, sequence value); - gl.uniformMatrix3fv(this.uniforms[key].uniformLocation, transpose, this.uniforms[key].value); - } - else if (type == "mat4") - { - // void uniformMatrix4fv(WebGLUniformLocation? location, GLboolean transpose, Float32Array value); - // void uniformMatrix4fv(WebGLUniformLocation? location, GLboolean transpose, sequence value); - gl.uniformMatrix4fv(this.uniforms[key].uniformLocation, transpose, this.uniforms[key].value); - } - else if (type == "sampler2D") - { - if (this.uniforms[key].value && this.uniforms[key].value.baseTexture.hasLoaded) - { - var texture = this.uniforms[key].value.baseTexture._glTexture; - var image = this.uniforms[key].value.baseTexture.source; - var format = gl.RGBA; - - if (this.uniforms[key].format && this.uniforms[key].format == 'luminance') - { - format = gl.LUMINANCE; - } - - gl.activeTexture(gl['TEXTURE' + this.textureCount]); - - if (this.uniforms[key].wrap) - { - if (this.uniforms[key].wrap == 'no-repeat' || this.uniforms[key].wrap === false) - { - this.createGLTextureLinear(gl, image, texture); - } - else if (this.uniforms[key].wrap == 'repeat' || this.uniforms[key].wrap === true) - { - this.createGLTexture(gl, image, format, texture); - } - else if (this.uniforms[key].wrap == 'nearest-repeat') - { - this.createGLTextureNearestRepeat(gl, image, texture); - } - else if (this.uniforms[key].wrap == 'nearest') - { - this.createGLTextureNearest(gl, image, texture); - } - else if (this.uniforms[key].wrap == 'audio') - { - this.createAudioTexture(gl, texture); - } - else if (this.uniforms[key].wrap == 'keyboard') - { - this.createKeyboardTexture(gl, texture); - } - } - else - { - this.createGLTextureLinear(gl, image, texture); - } - - gl.uniform1i(this.uniforms[key].uniformLocation, this.textureCount); - - this.textureCount++; - } - } - } - -}; - -/** -* Binds the given texture and image data. The texture is set to REPEAT. -* Code based on Effects.js from ShaderToy.com -* @method PIXI.PixiShader#createGLTexture -*/ -PIXI.PixiShader.prototype.createGLTexture = function(gl, image, format, texture) -{ - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, image); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); - gl.generateMipmap(gl.TEXTURE_2D); -} - -/** -* Binds the given texture and image data. The texture is set to CLAMP_TO_EDGE. -* Code based on Effects.js from ShaderToy.com -* @method PIXI.PixiShader#createGLTextureLinear -*/ -PIXI.PixiShader.prototype.createGLTextureLinear = function(gl, image, texture) -{ - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -} - -/** -* Binds the given texture and image data. The texture is set to REPEAT with NEAREST. -* Code based on Effects.js from ShaderToy.com -* @method PIXI.PixiShader#createGLTextureNearestRepeat -*/ -PIXI.PixiShader.prototype.createGLTextureNearestRepeat = function(gl, image, texture) -{ - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -} - -/** -* Binds the given texture and image data. The texture is set to CLAMP_TO_EDGE with NEAREST. -* Code based on Effects.js from ShaderToy.com -* @method PIXI.PixiShader#createGLTextureNearest -*/ -PIXI.PixiShader.prototype.createGLTextureNearest = function(gl, image, texture) -{ - gl.bindTexture(gl.TEXTURE_2D, texture); - gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -} - -/** -* Binds the given texture data. The texture is set to CLAMP_TO_EDGE with LUMINANCE. Designed for use with real-time audio data. -* Code based on Effects.js from ShaderToy.com -* @method PIXI.PixiShader#createAudioTexture -*/ -PIXI.PixiShader.prototype.createAudioTexture = function(gl, texture) -{ - gl.bindTexture(gl.TEXTURE_2D, texture ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) ; - gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, 512, 2, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, null); -} - -/** -* Binds the given texture data. The texture is set to CLAMP_TO_EDGE with LUMINANCE. Designed for use with keyboard input data. -* Code based on Effects.js from ShaderToy.com -* @method PIXI.PixiShader#createKeyboardTexture -*/ -PIXI.PixiShader.prototype.createKeyboardTexture = function(gl, texture) -{ - gl.bindTexture(gl.TEXTURE_2D, texture ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) ; - gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, 256, 2, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, null); -} - -PIXI.PixiShader.defaultVertexSrc = [ - - "attribute vec2 aVertexPosition;", - "attribute vec2 aTextureCoord;", - "attribute float aColor;", - - "uniform vec2 projectionVector;", - "uniform vec2 offsetVector;", - "varying vec2 vTextureCoord;", - - "varying float vColor;", - - "const vec2 center = vec2(-1.0, 1.0);", - - "void main(void) {", - "gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);", - "vTextureCoord = aTextureCoord;", - "vColor = aColor;", - "}" -]; - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -PIXI.PrimitiveShader = function() -{ - // the webGL program.. - this.program; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec4 vColor;", - "void main(void) {", - "gl_FragColor = vColor;", - "}" - ]; - - this.vertexSrc = [ - "attribute vec2 aVertexPosition;", - "attribute vec4 aColor;", - "uniform mat3 translationMatrix;", - "uniform vec2 projectionVector;", - "uniform vec2 offsetVector;", - "uniform float alpha;", - "varying vec4 vColor;", - "void main(void) {", - "vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);", - "v -= offsetVector.xyx;", - "gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);", - "vColor = aColor * alpha;", - "}" - ]; - -} - -PIXI.PrimitiveShader.prototype.init = function() -{ - var program = PIXI.compileProgram(this.vertexSrc, this.fragmentSrc); - - var gl = PIXI.gl; - - gl.useProgram(program); - - // get and store the uniforms for the shader - this.projectionVector = gl.getUniformLocation(program, "projectionVector"); - this.offsetVector = gl.getUniformLocation(program, "offsetVector"); - - // get and store the attributes - this.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition"); - this.colorAttribute = gl.getAttribLocation(program, "aColor"); - - this.translationMatrix = gl.getUniformLocation(program, "translationMatrix"); - this.alpha = gl.getUniformLocation(program, "alpha"); - - this.program = program; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -PIXI.StripShader = function() -{ - // the webGL program.. - this.program; - - this.fragmentSrc = [ - "precision mediump float;", - "varying vec2 vTextureCoord;", - "varying float vColor;", - "uniform float alpha;", - "uniform sampler2D uSampler;", - "void main(void) {", - "gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y));", - "gl_FragColor = gl_FragColor * alpha;", - "}" - ]; - - this.vertexSrc = [ - "attribute vec2 aVertexPosition;", - "attribute vec2 aTextureCoord;", - "attribute float aColor;", - "uniform mat3 translationMatrix;", - "uniform vec2 projectionVector;", - "varying vec2 vTextureCoord;", - "varying vec2 offsetVector;", - "varying float vColor;", - "void main(void) {", - "vec3 v = translationMatrix * vec3(aVertexPosition, 1.0);", - "v -= offsetVector.xyx;", - "gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / projectionVector.y + 1.0 , 0.0, 1.0);", - "vTextureCoord = aTextureCoord;", - "vColor = aColor;", - "}" - ]; -} - -PIXI.StripShader.prototype.init = function() -{ - var program = PIXI.compileProgram(this.vertexSrc, this.fragmentSrc) - - var gl = PIXI.gl; - - gl.useProgram(program); - - // get and store the uniforms for the shader - this.uSampler = gl.getUniformLocation(program, "uSampler"); - this.projectionVector = gl.getUniformLocation(program, "projectionVector"); - this.offsetVector = gl.getUniformLocation(program, "offsetVector"); - this.colorAttribute = gl.getAttribLocation(program, "aColor"); - //this.dimensions = gl.getUniformLocation(this.program, "dimensions"); - - // get and store the attributes - this.aVertexPosition = gl.getAttribLocation(program, "aVertexPosition"); - this.aTextureCoord = gl.getAttribLocation(program, "aTextureCoord"); - - this.translationMatrix = gl.getUniformLocation(program, "translationMatrix"); - this.alpha = gl.getUniformLocation(program, "alpha"); - - this.program = program; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -PIXI._batchs = []; - -/** - * @private - */ -PIXI._getBatch = function(gl) -{ - if(PIXI._batchs.length == 0) - { - return new PIXI.WebGLBatch(gl); - } - else - { - return PIXI._batchs.pop(); - } -} - -/** - * @private - */ -PIXI._returnBatch = function(batch) -{ - batch.clean(); - PIXI._batchs.push(batch); -} - -/** - * @private - */ -PIXI._restoreBatchs = function(gl) -{ - for (var i=0; i < PIXI._batchs.length; i++) - { - PIXI._batchs[i].restoreLostContext(gl); - }; -} - -/** - * A WebGLBatch Enables a group of sprites to be drawn using the same settings. - * if a group of sprites all have the same baseTexture and blendMode then they can be grouped into a batch. - * All the sprites in a batch can then be drawn in one go by the GPU which is hugely efficient. ALL sprites - * in the webGL renderer are added to a batch even if the batch only contains one sprite. Batching is handled - * automatically by the webGL renderer. A good tip is: the smaller the number of batchs there are, the faster - * the webGL renderer will run. - * - * @class WebGLBatch - * @constructor - * @param gl {WebGLContext} an instance of the webGL context - */ -PIXI.WebGLBatch = function(gl) -{ - this.gl = gl; - - this.size = 0; - - this.vertexBuffer = gl.createBuffer(); - this.indexBuffer = gl.createBuffer(); - this.uvBuffer = gl.createBuffer(); - this.colorBuffer = gl.createBuffer(); - this.blendMode = PIXI.blendModes.NORMAL; - this.dynamicSize = 1; -} - -// constructor -PIXI.WebGLBatch.prototype.constructor = PIXI.WebGLBatch; - -/** - * Cleans the batch so that is can be returned to an object pool and reused - * - * @method clean - */ -PIXI.WebGLBatch.prototype.clean = function() -{ - this.verticies = []; - this.uvs = []; - this.indices = []; - this.colors = []; - this.dynamicSize = 1; - this.texture = null; - this.last = null; - this.size = 0; - this.head; - this.tail; -} - -/** - * Recreates the buffers in the event of a context loss - * - * @method restoreLostContext - * @param gl {WebGLContext} - */ -PIXI.WebGLBatch.prototype.restoreLostContext = function(gl) -{ - this.gl = gl; - this.vertexBuffer = gl.createBuffer(); - this.indexBuffer = gl.createBuffer(); - this.uvBuffer = gl.createBuffer(); - this.colorBuffer = gl.createBuffer(); -} - -/** - * inits the batch's texture and blend mode based if the supplied sprite - * - * @method init - * @param sprite {Sprite} the first sprite to be added to the batch. Only sprites with - * the same base texture and blend mode will be allowed to be added to this batch - */ -PIXI.WebGLBatch.prototype.init = function(sprite) -{ - sprite.batch = this; - this.dirty = true; - this.blendMode = sprite.blendMode; - this.texture = sprite.texture.baseTexture; - this.head = sprite; - this.tail = sprite; - this.size = 1; - - this.growBatch(); -} - -/** - * inserts a sprite before the specified sprite - * - * @method insertBefore - * @param sprite {Sprite} the sprite to be added - * @param nextSprite {nextSprite} the first sprite will be inserted before this sprite - */ -PIXI.WebGLBatch.prototype.insertBefore = function(sprite, nextSprite) -{ - this.size++; - - sprite.batch = this; - this.dirty = true; - var tempPrev = nextSprite.__prev; - nextSprite.__prev = sprite; - sprite.__next = nextSprite; - - if(tempPrev) - { - sprite.__prev = tempPrev; - tempPrev.__next = sprite; - } - else - { - this.head = sprite; - } -} - -/** - * inserts a sprite after the specified sprite - * - * @method insertAfter - * @param sprite {Sprite} the sprite to be added - * @param previousSprite {Sprite} the first sprite will be inserted after this sprite - */ -PIXI.WebGLBatch.prototype.insertAfter = function(sprite, previousSprite) -{ - this.size++; - - sprite.batch = this; - this.dirty = true; - - var tempNext = previousSprite.__next; - previousSprite.__next = sprite; - sprite.__prev = previousSprite; - - if(tempNext) - { - sprite.__next = tempNext; - tempNext.__prev = sprite; - } - else - { - this.tail = sprite - } -} - -/** - * removes a sprite from the batch - * - * @method remove - * @param sprite {Sprite} the sprite to be removed - */ -PIXI.WebGLBatch.prototype.remove = function(sprite) -{ - this.size--; - - if(this.size == 0) - { - sprite.batch = null; - sprite.__prev = null; - sprite.__next = null; - return; - } - - if(sprite.__prev) - { - sprite.__prev.__next = sprite.__next; - } - else - { - this.head = sprite.__next; - this.head.__prev = null; - } - - if(sprite.__next) - { - sprite.__next.__prev = sprite.__prev; - } - else - { - this.tail = sprite.__prev; - this.tail.__next = null - } - - sprite.batch = null; - sprite.__next = null; - sprite.__prev = null; - this.dirty = true; -} - -/** - * Splits the batch into two with the specified sprite being the start of the new batch. - * - * @method split - * @param sprite {Sprite} the sprite that indicates where the batch should be split - * @return {WebGLBatch} the new batch - */ -PIXI.WebGLBatch.prototype.split = function(sprite) -{ - this.dirty = true; - - var batch = new PIXI.WebGLBatch(this.gl); - batch.init(sprite); - batch.texture = this.texture; - batch.tail = this.tail; - - this.tail = sprite.__prev; - this.tail.__next = null; - - sprite.__prev = null; - // return a splite batch! - - // TODO this size is wrong! - // need to recalculate :/ problem with a linked list! - // unless it gets calculated in the "clean"? - - // need to loop through items as there is no way to know the length on a linked list :/ - var tempSize = 0; - while(sprite) - { - tempSize++; - sprite.batch = batch; - sprite = sprite.__next; - } - - batch.size = tempSize; - this.size -= tempSize; - - return batch; -} - -/** - * Merges two batchs together - * - * @method merge - * @param batch {WebGLBatch} the batch that will be merged - */ -PIXI.WebGLBatch.prototype.merge = function(batch) -{ - this.dirty = true; - - this.tail.__next = batch.head; - batch.head.__prev = this.tail; - - this.size += batch.size; - - this.tail = batch.tail; - - var sprite = batch.head; - while(sprite) - { - sprite.batch = this; - sprite = sprite.__next; - } -} - -/** - * Grows the size of the batch. As the elements in the batch cannot have a dynamic size this - * function is used to increase the size of the batch. It also creates a little extra room so - * that the batch does not need to be resized every time a sprite is added - * - * @method growBatch - */ -PIXI.WebGLBatch.prototype.growBatch = function() -{ - var gl = this.gl; - if( this.size == 1) - { - this.dynamicSize = 1; - } - else - { - this.dynamicSize = this.size * 1.5 - } - // grow verts - this.verticies = new Float32Array(this.dynamicSize * 8); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); - gl.bufferData(gl.ARRAY_BUFFER,this.verticies , gl.DYNAMIC_DRAW); - - this.uvs = new Float32Array( this.dynamicSize * 8 ); - gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); - gl.bufferData(gl.ARRAY_BUFFER, this.uvs , gl.DYNAMIC_DRAW); - - this.dirtyUVS = true; - - this.colors = new Float32Array( this.dynamicSize * 4 ); - gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); - gl.bufferData(gl.ARRAY_BUFFER, this.colors , gl.DYNAMIC_DRAW); - - this.dirtyColors = true; - - this.indices = new Uint16Array(this.dynamicSize * 6); - var length = this.indices.length/6; - - for (var i=0; i < length; i++) - { - var index2 = i * 6; - var index3 = i * 4; - this.indices[index2 + 0] = index3 + 0; - this.indices[index2 + 1] = index3 + 1; - this.indices[index2 + 2] = index3 + 2; - this.indices[index2 + 3] = index3 + 0; - this.indices[index2 + 4] = index3 + 2; - this.indices[index2 + 5] = index3 + 3; - }; - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW); -} - -/** - * Refresh's all the data in the batch and sync's it with the webGL buffers - * - * @method refresh - */ -PIXI.WebGLBatch.prototype.refresh = function() -{ - var gl = this.gl; - - if (this.dynamicSize < this.size) - { - this.growBatch(); - } - - var indexRun = 0; - var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index; - var a, b, c, d, tx, ty; - - var displayObject = this.head; - - while(displayObject) - { - index = indexRun * 8; - - var texture = displayObject.texture; - - var frame = texture.frame; - var tw = texture.baseTexture.width; - var th = texture.baseTexture.height; - - this.uvs[index + 0] = frame.x / tw; - this.uvs[index +1] = frame.y / th; - - this.uvs[index +2] = (frame.x + frame.width) / tw; - this.uvs[index +3] = frame.y / th; - - this.uvs[index +4] = (frame.x + frame.width) / tw; - this.uvs[index +5] = (frame.y + frame.height) / th; - - this.uvs[index +6] = frame.x / tw; - this.uvs[index +7] = (frame.y + frame.height) / th; - - displayObject.updateFrame = false; - - colorIndex = indexRun * 4; - this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha; - - displayObject = displayObject.__next; - - indexRun ++; - } - - this.dirtyUVS = true; - this.dirtyColors = true; -} - -/** - * Updates all the relevant geometry and uploads the data to the GPU - * - * @method update - */ -PIXI.WebGLBatch.prototype.update = function() -{ - var gl = this.gl; - var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3 - - var a, b, c, d, tx, ty; - - var indexRun = 0; - - var displayObject = this.head; - var verticies = this.verticies; - var uvs = this.uvs; - var colors = this.colors; - - while(displayObject) - { - if(displayObject.vcount === PIXI.visibleCount) - { - width = displayObject.texture.frame.width; - height = displayObject.texture.frame.height; - - // TODO trim?? - aX = displayObject.anchor.x;// - displayObject.texture.trim.x - aY = displayObject.anchor.y; //- displayObject.texture.trim.y - w0 = width * (1-aX); - w1 = width * -aX; - - h0 = height * (1-aY); - h1 = height * -aY; - - index = indexRun * 8; - - worldTransform = displayObject.worldTransform; - - a = worldTransform[0]; - b = worldTransform[3]; - c = worldTransform[1]; - d = worldTransform[4]; - tx = worldTransform[2]; - ty = worldTransform[5]; - - verticies[index + 0 ] = a * w1 + c * h1 + tx; - verticies[index + 1 ] = d * h1 + b * w1 + ty; - - verticies[index + 2 ] = a * w0 + c * h1 + tx; - verticies[index + 3 ] = d * h1 + b * w0 + ty; - - verticies[index + 4 ] = a * w0 + c * h0 + tx; - verticies[index + 5 ] = d * h0 + b * w0 + ty; - - verticies[index + 6] = a * w1 + c * h0 + tx; - verticies[index + 7] = d * h0 + b * w1 + ty; - - if(displayObject.updateFrame || displayObject.texture.updateFrame) - { - this.dirtyUVS = true; - - var texture = displayObject.texture; - - var frame = texture.frame; - var tw = texture.baseTexture.width; - var th = texture.baseTexture.height; - - uvs[index + 0] = frame.x / tw; - uvs[index +1] = frame.y / th; - - uvs[index +2] = (frame.x + frame.width) / tw; - uvs[index +3] = frame.y / th; - - uvs[index +4] = (frame.x + frame.width) / tw; - uvs[index +5] = (frame.y + frame.height) / th; - - uvs[index +6] = frame.x / tw; - uvs[index +7] = (frame.y + frame.height) / th; - - displayObject.updateFrame = false; - } - - // TODO this probably could do with some optimisation.... - if(displayObject.cacheAlpha != displayObject.worldAlpha) - { - displayObject.cacheAlpha = displayObject.worldAlpha; - - var colorIndex = indexRun * 4; - colors[colorIndex] = colors[colorIndex + 1] = colors[colorIndex + 2] = colors[colorIndex + 3] = displayObject.worldAlpha; - this.dirtyColors = true; - } - } - else - { - index = indexRun * 8; - - verticies[index + 0 ] = verticies[index + 1 ] = verticies[index + 2 ] = verticies[index + 3 ] = verticies[index + 4 ] = verticies[index + 5 ] = verticies[index + 6] = verticies[index + 7] = 0; - } - - indexRun++; - displayObject = displayObject.__next; - } -} - -/** - * Draws the batch to the frame buffer - * - * @method render - */ -PIXI.WebGLBatch.prototype.render = function(start, end) -{ - start = start || 0; - - if(end == undefined)end = this.size; - - if(this.dirty) - { - this.refresh(); - this.dirty = false; - } - - if (this.size == 0)return; - - this.update(); - var gl = this.gl; - - //TODO optimize this! - - var shaderProgram = PIXI.defaultShader; - - //gl.useProgram(shaderProgram); - - // update the verts.. - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); - // ok.. - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.verticies) - gl.vertexAttribPointer(shaderProgram.aVertexPosition, 2, gl.FLOAT, false, 0, 0); - // update the uvs - //var isDefault = (shaderProgram == PIXI.shaderProgram) - - gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); - - if(this.dirtyUVS) - { - this.dirtyUVS = false; - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvs); - } - - gl.vertexAttribPointer(shaderProgram.aTextureCoord, 2, gl.FLOAT, false, 0, 0); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, this.texture._glTexture); - - // update color! - gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer); - - if(this.dirtyColors) - { - this.dirtyColors = false; - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.colors); - } - - gl.vertexAttribPointer(shaderProgram.colorAttribute, 1, gl.FLOAT, false, 0, 0); - // dont need to upload! - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); - - var len = end - start; - - // DRAW THAT this! - gl.drawElements(gl.TRIANGLES, len * 6, gl.UNSIGNED_SHORT, start * 2 * 6 ); -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -PIXI.WebGLFilterManager = function(transparent) -{ - this.transparent = transparent; - - this.filterStack = []; - this.texturePool = []; - - this.offsetX = 0; - this.offsetY = 0; - - this.initShaderBuffers(); -} - -// API - -PIXI.WebGLFilterManager.prototype.begin = function(projection, buffer) -{ - this.width = projection.x * 2; - this.height = -projection.y * 2; - this.buffer = buffer; -} - -PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock) -{ - var gl = PIXI.gl; - - // filter program - // OPTIMISATION - the first filter is free if its a simple color change? - this.filterStack.push(filterBlock); - - var filter = filterBlock.filterPasses[0]; - - - - this.offsetX += filterBlock.target.filterArea.x; - this.offsetY += filterBlock.target.filterArea.y; - - - - - - var texture = this.texturePool.pop(); - if(!texture)texture = new PIXI.FilterTexture(this.width, this.height); - - gl.bindTexture(gl.TEXTURE_2D, texture.texture); - - this.getBounds(filterBlock.target); - - // addpadding? - //displayObject.filterArea.x - - var filterArea = filterBlock.target.filterArea; - - var padidng = filter.padding; - filterArea.x -= padidng; - filterArea.y -= padidng; - filterArea.width += padidng * 2; - filterArea.height += padidng * 2; - - // cap filter to screen size.. - if(filterArea.x < 0)filterArea.x = 0; - if(filterArea.width > this.width)filterArea.width = this.width; - if(filterArea.y < 0)filterArea.y = 0; - if(filterArea.height > this.height)filterArea.height = this.height; - - - //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer); - - // console.log(filterArea) - // set view port - gl.viewport(0, 0, filterArea.width, filterArea.height); - - PIXI.projection.x = filterArea.width/2; - PIXI.projection.y = -filterArea.height/2; - - PIXI.offset.x = -filterArea.x; - PIXI.offset.y = -filterArea.y; - - //console.log(PIXI.defaultShader.projectionVector) - // update projection - gl.uniform2f(PIXI.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2); - gl.uniform2f(PIXI.defaultShader.offsetVector, -filterArea.x, -filterArea.y); - //PIXI.primitiveProgram - - gl.colorMask(true, true, true, true); - gl.clearColor(0,0,0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - - //filter.texture = texture; - filterBlock._glFilterTexture = texture; - - //console.log("PUSH") -} - - -PIXI.WebGLFilterManager.prototype.popFilter = function() -{ - - var gl = PIXI.gl; - - var filterBlock = this.filterStack.pop(); - - - - var filterArea = filterBlock.target.filterArea; - - var texture = filterBlock._glFilterTexture; - - if(filterBlock.filterPasses.length > 1) - { - gl.viewport(0, 0, filterArea.width, filterArea.height); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); - - this.vertexArray[0] = 0; - this.vertexArray[1] = filterArea.height; - - this.vertexArray[2] = filterArea.width; - this.vertexArray[3] = filterArea.height; - - this.vertexArray[4] = 0; - this.vertexArray[5] = 0; - - this.vertexArray[6] = filterArea.width; - this.vertexArray[7] = 0; - - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray); - - - gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); - // nnow set the uvs.. - this.uvArray[2] = filterArea.width/this.width; - this.uvArray[5] = filterArea.height/this.height; - this.uvArray[6] = filterArea.width/this.width; - this.uvArray[7] = filterArea.height/this.height; - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray); - - var inputTexture = texture; - var outputTexture = this.texturePool.pop(); - if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.width, this.height); - - // need to clear this FBO as it may have some left over elements from a prvious filter. - gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); - gl.clear(gl.COLOR_BUFFER_BIT); - - gl.disable(gl.BLEND); - - for (var i = 0; i < filterBlock.filterPasses.length-1; i++) - { - var filterPass = filterBlock.filterPasses[i]; - - gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer ); - - // set texture - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture); - - // draw texture.. - //filterPass.applyFilterPass(filterArea.width, filterArea.height); - this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height); - - // swap the textures.. - var temp = inputTexture; - inputTexture = outputTexture; - outputTexture = temp; - - }; - - gl.enable(gl.BLEND); - - texture = inputTexture; - this.texturePool.push(outputTexture); - } - - var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1]; - - this.offsetX -= filterArea.x; - this.offsetY -= filterArea.y; - - - var sizeX = this.width; - var sizeY = this.height; - - var offsetX = 0; - var offsetY = 0; - - var buffer = this.buffer; - - // time to render the filters texture to the previous scene - if(this.filterStack.length === 0) - { - gl.colorMask(true, true, true, this.transparent); - } - else - { - var currentFilter = this.filterStack[this.filterStack.length-1]; - var filterArea = currentFilter.target.filterArea; - - sizeX = filterArea.width; - sizeY = filterArea.height; - - offsetX = filterArea.x; - offsetY = filterArea.y; - - buffer = currentFilter._glFilterTexture.frameBuffer; - } - - - - // TODO need toremove thease global elements.. - PIXI.projection.x = sizeX/2; - PIXI.projection.y = -sizeY/2; - - PIXI.offset.x = offsetX; - PIXI.offset.y = offsetY; - - - var filterArea = filterBlock.target.filterArea; - var x = filterArea.x-offsetX; - var y = filterArea.y-offsetY; - - // update the buffers.. - // make sure to flip the y! - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); - - this.vertexArray[0] = x; - this.vertexArray[1] = y + filterArea.height; - - this.vertexArray[2] = x + filterArea.width; - this.vertexArray[3] = y + filterArea.height; - - this.vertexArray[4] = x; - this.vertexArray[5] = y; - - this.vertexArray[6] = x + filterArea.width; - this.vertexArray[7] = y; - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); - - this.uvArray[2] = filterArea.width/this.width; - this.uvArray[5] = filterArea.height/this.height; - this.uvArray[6] = filterArea.width/this.width; - this.uvArray[7] = filterArea.height/this.height; - - gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray); - - gl.viewport(0, 0, sizeX, sizeY); - // bind the buffer - gl.bindFramebuffer(gl.FRAMEBUFFER, buffer ); - - // set texture - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, texture.texture); - - // apply! - //filter.applyFilterPass(sizeX, sizeY); - this.applyFilterPass(filter, filterArea, sizeX, sizeY); - - // now restore the regular shader.. - gl.useProgram(PIXI.defaultShader.program); - gl.uniform2f(PIXI.defaultShader.projectionVector, sizeX/2, -sizeY/2); - gl.uniform2f(PIXI.defaultShader.offsetVector, -offsetX, -offsetY); - - // return the texture to the pool - this.texturePool.push(texture); - filterBlock._glFilterTexture = null; -} - -PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height) -{ - // use program - var gl = PIXI.gl; - - if(!filter.shader) - { - var shader = new PIXI.PixiShader(); - - shader.fragmentSrc = filter.fragmentSrc; - shader.uniforms = filter.uniforms; - shader.init(); - - filter.shader = shader; - } - - var shader = filter.shader; - - // set the shader - gl.useProgram(shader.program); - - gl.uniform2f(shader.projectionVector, width/2, -height/2); - gl.uniform2f(shader.offsetVector, 0,0) - - if(filter.uniforms.dimensions) - { - //console.log(filter.uniforms.dimensions) - filter.uniforms.dimensions.value[0] = this.width;//width; - filter.uniforms.dimensions.value[1] = this.height;//height; - filter.uniforms.dimensions.value[2] = this.vertexArray[0]; - filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height; - // console.log(this.vertexArray[5]) - } - - shader.syncUniforms(); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); - gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); - gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); - - // draw the filter... - gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 ); -} - -PIXI.WebGLFilterManager.prototype.initShaderBuffers = function() -{ - var gl = PIXI.gl; - - // create some buffers - this.vertexBuffer = gl.createBuffer(); - this.uvBuffer = gl.createBuffer(); - this.indexBuffer = gl.createBuffer(); - - // bind and upload the vertexs.. - // keep a refferance to the vertexFloatData.. - this.vertexArray = new Float32Array([0.0, 0.0, - 1.0, 0.0, - 0.0, 1.0, - 1.0, 1.0]); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); - gl.bufferData( - gl.ARRAY_BUFFER, - this.vertexArray, - gl.STATIC_DRAW); - - - // bind and upload the uv buffer - this.uvArray = new Float32Array([0.0, 0.0, - 1.0, 0.0, - 0.0, 1.0, - 1.0, 1.0]); - - gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer); - gl.bufferData( - gl.ARRAY_BUFFER, - this.uvArray, - gl.STATIC_DRAW); - - // bind and upload the index - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); - gl.bufferData( - gl.ELEMENT_ARRAY_BUFFER, - new Uint16Array([0, 1, 2, 1, 3, 2]), - gl.STATIC_DRAW); -} - -PIXI.WebGLFilterManager.prototype.getBounds = function(displayObject) -{ - // time to get the width and height of the object! - var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, doTest; - var a, b, c, d, tx, ty, x1, x2, x3, x4, y1, y2, y3, y4; - - var tempObject = displayObject.first; - var testObject = displayObject.last._iNext; - - var maxX = -Infinity; - var maxY = -Infinity; - - var minX = Infinity; - var minY = Infinity; - - do - { - // TODO can be optimized! - what if there is no scale / rotation? - - if(tempObject.visible) - { - if(tempObject instanceof PIXI.Sprite) - { - width = tempObject.texture.frame.width; - height = tempObject.texture.frame.height; - - // TODO trim?? - aX = tempObject.anchor.x; - aY = tempObject.anchor.y; - w0 = width * (1-aX); - w1 = width * -aX; - - h0 = height * (1-aY); - h1 = height * -aY; - - doTest = true; - } - else if(tempObject instanceof PIXI.Graphics) - { - tempObject.updateFilterBounds(); - - var bounds = tempObject.bounds; - - width = bounds.width; - height = bounds.height; - - w0 = bounds.x - w1 = bounds.x + bounds.width; - - h0 = bounds.y - h1 = bounds.y + bounds.height; - - doTest = true; - } - } - - if(doTest) - { - worldTransform = tempObject.worldTransform; - - a = worldTransform[0]; - b = worldTransform[3]; - c = worldTransform[1]; - d = worldTransform[4]; - tx = worldTransform[2]; - ty = worldTransform[5]; - - x1 = a * w1 + c * h1 + tx; - y1 = d * h1 + b * w1 + ty; - - x2 = a * w0 + c * h1 + tx; - y2 = d * h1 + b * w0 + ty; - - x3 = a * w0 + c * h0 + tx; - y3 = d * h0 + b * w0 + ty; - - x4 = a * w1 + c * h0 + tx; - y4 = d * h0 + b * w1 + ty; - - minX = x1 < minX ? x1 : minX; - minX = x2 < minX ? x2 : minX; - minX = x3 < minX ? x3 : minX; - minX = x4 < minX ? x4 : minX; - - minY = y1 < minY ? y1 : minY; - minY = y2 < minY ? y2 : minY; - minY = y3 < minY ? y3 : minY; - minY = y4 < minY ? y4 : minY; - - maxX = x1 > maxX ? x1 : maxX; - maxX = x2 > maxX ? x2 : maxX; - maxX = x3 > maxX ? x3 : maxX; - maxX = x4 > maxX ? x4 : maxX; - - maxY = y1 > maxY ? y1 : maxY; - maxY = y2 > maxY ? y2 : maxY; - maxY = y3 > maxY ? y3 : maxY; - maxY = y4 > maxY ? y4 : maxY; - } - - doTest = false; - tempObject = tempObject._iNext; - - } - while(tempObject != testObject) - - // maximum bounds is the size of the screen.. - //minX = minX > 0 ? minX : 0; - //minY = minY > 0 ? minY : 0; - - displayObject.filterArea.x = minX; - displayObject.filterArea.y = minY; - -// console.log(maxX+ " : " + minX) - displayObject.filterArea.width = maxX - minX; - displayObject.filterArea.height = maxY - minY; -} - -PIXI.FilterTexture = function(width, height) -{ - var gl = PIXI.gl; - - // next time to create a frame buffer and texture - this.frameBuffer = gl.createFramebuffer(); - this.texture = gl.createTexture(); - - gl.bindTexture(gl.TEXTURE_2D, this.texture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer ); - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer ); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0); - - this.resize(width, height); -} - -PIXI.FilterTexture.prototype.resize = function(width, height) -{ - this.width = width; - this.height = height; - - var gl = PIXI.gl; - - gl.bindTexture(gl.TEXTURE_2D, this.texture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - -} -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * A set of functions used by the webGL renderer to draw the primitive graphics data - * - * @class CanvasGraphics - */ -PIXI.WebGLGraphics = function() -{ - -} - -/** - * Renders the graphics object - * - * @static - * @private - * @method renderGraphics - * @param graphics {Graphics} - * @param projection {Object} - */ -PIXI.WebGLGraphics.renderGraphics = function(graphics, projection) -{ - var gl = PIXI.gl; - - if(!graphics._webGL)graphics._webGL = {points:[], indices:[], lastIndex:0, - buffer:gl.createBuffer(), - indexBuffer:gl.createBuffer()}; - - if(graphics.dirty) - { - graphics.dirty = false; - - if(graphics.clearDirty) - { - graphics.clearDirty = false; - - graphics._webGL.lastIndex = 0; - graphics._webGL.points = []; - graphics._webGL.indices = []; - - } - - PIXI.WebGLGraphics.updateGraphics(graphics); - } - - PIXI.activatePrimitiveShader(); - - // This could be speeded up fo sure! - var m = PIXI.mat3.clone(graphics.worldTransform); - - PIXI.mat3.transpose(m); - - // set the matrix transform for the - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - - gl.uniformMatrix3fv(PIXI.primitiveShader.translationMatrix, false, m); - - gl.uniform2f(PIXI.primitiveShader.projectionVector, projection.x, -projection.y); - gl.uniform2f(PIXI.primitiveShader.offsetVector, -PIXI.offset.x, -PIXI.offset.y); - - gl.uniform1f(PIXI.primitiveShader.alpha, graphics.worldAlpha); - gl.bindBuffer(gl.ARRAY_BUFFER, graphics._webGL.buffer); - - gl.vertexAttribPointer(PIXI.primitiveShader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0); - gl.vertexAttribPointer(PIXI.primitiveShader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4); - - // set the index buffer! - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, graphics._webGL.indexBuffer); - - - gl.drawElements(gl.TRIANGLE_STRIP, graphics._webGL.indices.length, gl.UNSIGNED_SHORT, 0 ); - - PIXI.deactivatePrimitiveShader(); - - - // return to default shader... -// PIXI.activateShader(PIXI.defaultShader); -} - -/** - * Updates the graphics object - * - * @static - * @private - * @method updateGraphics - * @param graphics {Graphics} - */ -PIXI.WebGLGraphics.updateGraphics = function(graphics) -{ - for (var i=graphics._webGL.lastIndex; i < graphics.graphicsData.length; i++) - { - var data = graphics.graphicsData[i]; - - if(data.type == PIXI.Graphics.POLY) - { - if(data.fill) - { - if(data.points.length>3) - PIXI.WebGLGraphics.buildPoly(data, graphics._webGL); - } - - if(data.lineWidth > 0) - { - PIXI.WebGLGraphics.buildLine(data, graphics._webGL); - } - } - else if(data.type == PIXI.Graphics.RECT) - { - PIXI.WebGLGraphics.buildRectangle(data, graphics._webGL); - } - else if(data.type == PIXI.Graphics.CIRC || data.type == PIXI.Graphics.ELIP) - { - PIXI.WebGLGraphics.buildCircle(data, graphics._webGL); - } - }; - - graphics._webGL.lastIndex = graphics.graphicsData.length; - - var gl = PIXI.gl; - - graphics._webGL.glPoints = new Float32Array(graphics._webGL.points); - - gl.bindBuffer(gl.ARRAY_BUFFER, graphics._webGL.buffer); - gl.bufferData(gl.ARRAY_BUFFER, graphics._webGL.glPoints, gl.STATIC_DRAW); - - graphics._webGL.glIndicies = new Uint16Array(graphics._webGL.indices); - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, graphics._webGL.indexBuffer); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, graphics._webGL.glIndicies, gl.STATIC_DRAW); -} - -/** - * Builds a rectangle to draw - * - * @static - * @private - * @method buildRectangle - * @param graphics {Graphics} - * @param webGLData {Object} - */ -PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData) -{ - // --- // - // need to convert points to a nice regular data - // - var rectData = graphicsData.points; - var x = rectData[0]; - var y = rectData[1]; - var width = rectData[2]; - var height = rectData[3]; - - - if(graphicsData.fill) - { - var color = HEXtoRGB(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var verts = webGLData.points; - var indices = webGLData.indices; - - var vertPos = verts.length/6; - - // start - verts.push(x, y); - verts.push(r, g, b, alpha); - - verts.push(x + width, y); - verts.push(r, g, b, alpha); - - verts.push(x , y + height); - verts.push(r, g, b, alpha); - - verts.push(x + width, y + height); - verts.push(r, g, b, alpha); - - // insert 2 dead triangles.. - indices.push(vertPos, vertPos, vertPos+1, vertPos+2, vertPos+3, vertPos+3) - } - - if(graphicsData.lineWidth) - { - graphicsData.points = [x, y, - x + width, y, - x + width, y + height, - x, y + height, - x, y]; - - PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); - } - -} - -/** - * Builds a circle to draw - * - * @static - * @private - * @method buildCircle - * @param graphics {Graphics} - * @param webGLData {Object} - */ -PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData) -{ - // --- // - // need to convert points to a nice regular data - // - var rectData = graphicsData.points; - var x = rectData[0]; - var y = rectData[1]; - var width = rectData[2]; - var height = rectData[3]; - - var totalSegs = 40; - var seg = (Math.PI * 2) / totalSegs ; - - if(graphicsData.fill) - { - var color = HEXtoRGB(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var verts = webGLData.points; - var indices = webGLData.indices; - - var vecPos = verts.length/6; - - indices.push(vecPos); - - for (var i=0; i < totalSegs + 1 ; i++) - { - verts.push(x,y, r, g, b, alpha); - - verts.push(x + Math.sin(seg * i) * width, - y + Math.cos(seg * i) * height, - r, g, b, alpha); - - indices.push(vecPos++, vecPos++); - }; - - indices.push(vecPos-1); - } - - if(graphicsData.lineWidth) - { - graphicsData.points = []; - - for (var i=0; i < totalSegs + 1; i++) - { - graphicsData.points.push(x + Math.sin(seg * i) * width, - y + Math.cos(seg * i) * height) - }; - - PIXI.WebGLGraphics.buildLine(graphicsData, webGLData); - } - -} - -/** - * Builds a line to draw - * - * @static - * @private - * @method buildLine - * @param graphics {Graphics} - * @param webGLData {Object} - */ -PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData) -{ - // TODO OPTIMISE! - - var wrap = true; - var points = graphicsData.points; - if(points.length == 0)return; - - // if the line width is an odd number add 0.5 to align to a whole pixel - if(graphicsData.lineWidth%2) - { - for (var i = 0; i < points.length; i++) { - points[i] += 0.5; - }; - } - - // get first and last point.. figure out the middle! - var firstPoint = new PIXI.Point( points[0], points[1] ); - var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); - - // if the first point is the last point - goona have issues :) - if(firstPoint.x == lastPoint.x && firstPoint.y == lastPoint.y) - { - points.pop(); - points.pop(); - - lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] ); - - var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5; - var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5; - - points.unshift(midPointX, midPointY); - points.push(midPointX, midPointY) - } - - var verts = webGLData.points; - var indices = webGLData.indices; - var length = points.length / 2; - var indexCount = points.length; - var indexStart = verts.length/6; - - // DRAW the Line - var width = graphicsData.lineWidth / 2; - - // sort color - var color = HEXtoRGB(graphicsData.lineColor); - var alpha = graphicsData.lineAlpha; - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var p1x, p1y, p2x, p2y, p3x, p3y; - var perpx, perpy, perp2x, perp2y, perp3x, perp3y; - var ipx, ipy; - var a1, b1, c1, a2, b2, c2; - var denom, pdist, dist; - - p1x = points[0]; - p1y = points[1]; - - p2x = points[2]; - p2y = points[3]; - - perpx = -(p1y - p2y); - perpy = p1x - p2x; - - dist = Math.sqrt(perpx*perpx + perpy*perpy); - - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - // start - verts.push(p1x - perpx , p1y - perpy, - r, g, b, alpha); - - verts.push(p1x + perpx , p1y + perpy, - r, g, b, alpha); - - for (var i = 1; i < length-1; i++) - { - p1x = points[(i-1)*2]; - p1y = points[(i-1)*2 + 1]; - - p2x = points[(i)*2] - p2y = points[(i)*2 + 1] - - p3x = points[(i+1)*2]; - p3y = points[(i+1)*2 + 1]; - - perpx = -(p1y - p2y); - perpy = p1x - p2x; - - dist = Math.sqrt(perpx*perpx + perpy*perpy); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - perp2x = -(p2y - p3y); - perp2y = p2x - p3x; - - dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y); - perp2x /= dist; - perp2y /= dist; - perp2x *= width; - perp2y *= width; - - a1 = (-perpy + p1y) - (-perpy + p2y); - b1 = (-perpx + p2x) - (-perpx + p1x); - c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y); - a2 = (-perp2y + p3y) - (-perp2y + p2y); - b2 = (-perp2x + p2x) - (-perp2x + p3x); - c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y); - - denom = a1*b2 - a2*b1; - - if(Math.abs(denom) < 0.1 ) - { - - denom+=10.1; - verts.push(p2x - perpx , p2y - perpy, - r, g, b, alpha); - - verts.push(p2x + perpx , p2y + perpy, - r, g, b, alpha); - - continue; - } - - px = (b1*c2 - b2*c1)/denom; - py = (a2*c1 - a1*c2)/denom; - - - pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y); - - - if(pdist > 140 * 140) - { - perp3x = perpx - perp2x; - perp3y = perpy - perp2y; - - dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y); - perp3x /= dist; - perp3y /= dist; - perp3x *= width; - perp3y *= width; - - verts.push(p2x - perp3x, p2y -perp3y); - verts.push(r, g, b, alpha); - - verts.push(p2x + perp3x, p2y +perp3y); - verts.push(r, g, b, alpha); - - verts.push(p2x - perp3x, p2y -perp3y); - verts.push(r, g, b, alpha); - - indexCount++; - } - else - { - - verts.push(px , py); - verts.push(r, g, b, alpha); - - verts.push(p2x - (px-p2x), p2y - (py - p2y)); - verts.push(r, g, b, alpha); - } - } - - p1x = points[(length-2)*2] - p1y = points[(length-2)*2 + 1] - - p2x = points[(length-1)*2] - p2y = points[(length-1)*2 + 1] - - perpx = -(p1y - p2y) - perpy = p1x - p2x; - - dist = Math.sqrt(perpx*perpx + perpy*perpy); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - - verts.push(p2x - perpx , p2y - perpy) - verts.push(r, g, b, alpha); - - verts.push(p2x + perpx , p2y + perpy) - verts.push(r, g, b, alpha); - - indices.push(indexStart); - - for (var i=0; i < indexCount; i++) - { - indices.push(indexStart++); - }; - - indices.push(indexStart-1); -} - -/** - * Builds a polygon to draw - * - * @static - * @private - * @method buildPoly - * @param graphics {Graphics} - * @param webGLData {Object} - */ -PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData) -{ - var points = graphicsData.points; - if(points.length < 6)return; - - // get first and last point.. figure out the middle! - var verts = webGLData.points; - var indices = webGLData.indices; - - var length = points.length / 2; - - // sort color - var color = HEXtoRGB(graphicsData.fillColor); - var alpha = graphicsData.fillAlpha; - var r = color[0] * alpha; - var g = color[1] * alpha; - var b = color[2] * alpha; - - var triangles = PIXI.PolyK.Triangulate(points); - - var vertPos = verts.length / 6; - - for (var i=0; i < triangles.length; i+=3) - { - indices.push(triangles[i] + vertPos); - indices.push(triangles[i] + vertPos); - indices.push(triangles[i+1] + vertPos); - indices.push(triangles[i+2] +vertPos); - indices.push(triangles[i+2] + vertPos); - }; - - for (var i = 0; i < length; i++) - { - verts.push(points[i * 2], points[i * 2 + 1], - r, g, b, alpha); - }; -} - -function HEXtoRGB(hex) { - return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255]; -} - - - - - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -PIXI._defaultFrame = new PIXI.Rectangle(0,0,1,1); - -// an instance of the gl context.. -// only one at the moment :/ -PIXI.gl; - -/** - * the WebGLRenderer is draws the stage and all its content onto a webGL enabled canvas. This renderer - * should be used for browsers support webGL. This Render works by automatically managing webGLBatchs. - * So no need for Sprite Batch's or Sprite Cloud's - * Dont forget to add the view to your DOM or you will not see anything :) - * - * @class WebGLRenderer - * @constructor - * @param width=0 {Number} the width of the canvas view - * @param height=0 {Number} the height of the canvas view - * @param view {Canvas} the canvas to use as a view, optional - * @param transparent=false {Boolean} the transparency of the render view, default false - * @param antialias=false {Boolean} sets antialias (only applicable in chrome at the moment) - * - */ -PIXI.WebGLRenderer = function(width, height, view, transparent, antialias) -{ - // do a catch.. only 1 webGL renderer.. - - this.transparent = !!transparent; - - this.width = width || 800; - this.height = height || 600; - - this.view = view || document.createElement( 'canvas' ); - this.view.width = this.width; - this.view.height = this.height; - - // deal with losing context.. - var scope = this; - this.view.addEventListener('webglcontextlost', function(event) { scope.handleContextLost(event); }, false) - this.view.addEventListener('webglcontextrestored', function(event) { scope.handleContextRestored(event); }, false) - - this.batchs = []; - - var options = { - alpha: this.transparent, - antialias:!!antialias, // SPEED UP?? - premultipliedAlpha:false, - stencil:true - } - - //try 'experimental-webgl' - try { - PIXI.gl = this.gl = this.view.getContext("experimental-webgl", options); - } catch (e) { - //try 'webgl' - try { - PIXI.gl = this.gl = this.view.getContext("webgl", options); - } catch (e) { - // fail, not able to get a context - throw new Error(" This browser does not support webGL. Try using the canvas renderer" + this); - } - } - - PIXI.initDefaultShaders(); - - - - - // PIXI.activateDefaultShader(); - - var gl = this.gl; - - gl.useProgram(PIXI.defaultShader.program); - - - PIXI.WebGLRenderer.gl = gl; - - this.batch = new PIXI.WebGLBatch(gl); - gl.disable(gl.DEPTH_TEST); - gl.disable(gl.CULL_FACE); - - gl.enable(gl.BLEND); - gl.colorMask(true, true, true, this.transparent); - - PIXI.projection = new PIXI.Point(400, 300); - PIXI.offset = new PIXI.Point(0, 0); - - // TODO remove thease globals.. - - this.resize(this.width, this.height); - this.contextLost = false; - - //PIXI.pushShader(PIXI.defaultShader); - - this.stageRenderGroup = new PIXI.WebGLRenderGroup(this.gl, this.transparent); - // this.stageRenderGroup. = this.transparent -} - -// constructor -PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer; - -/** - * Gets a new WebGLBatch from the pool - * - * @static - * @method getBatch - * @return {WebGLBatch} - * @private - */ -PIXI.WebGLRenderer.getBatch = function() -{ - if(PIXI._batchs.length == 0) - { - return new PIXI.WebGLBatch(PIXI.WebGLRenderer.gl); - } - else - { - return PIXI._batchs.pop(); - } -} - -/** - * Puts a batch back into the pool - * - * @static - * @method returnBatch - * @param batch {WebGLBatch} The batch to return - * @private - */ -PIXI.WebGLRenderer.returnBatch = function(batch) -{ - batch.clean(); - PIXI._batchs.push(batch); -} - -/** - * Renders the stage to its webGL view - * - * @method render - * @param stage {Stage} the Stage element to be rendered - */ -PIXI.WebGLRenderer.prototype.render = function(stage) -{ - if(this.contextLost)return; - - - // if rendering a new stage clear the batchs.. - if(this.__stage !== stage) - { - // TODO make this work - // dont think this is needed any more? - this.__stage = stage; - this.stageRenderGroup.setRenderable(stage); - } - - // update any textures - PIXI.WebGLRenderer.updateTextures(); - - // update the scene graph - PIXI.visibleCount++; - stage.updateTransform(); - - var gl = this.gl; - - // -- Does this need to be set every frame? -- // - gl.colorMask(true, true, true, this.transparent); - gl.viewport(0, 0, this.width, this.height); - - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - - gl.clearColor(stage.backgroundColorSplit[0],stage.backgroundColorSplit[1],stage.backgroundColorSplit[2], !this.transparent); - gl.clear(gl.COLOR_BUFFER_BIT); - - // HACK TO TEST - - this.stageRenderGroup.backgroundColor = stage.backgroundColorSplit; - - PIXI.projection.x = this.width/2; - PIXI.projection.y = -this.height/2; - - this.stageRenderGroup.render(PIXI.projection); - - // interaction - // run interaction! - if(stage.interactive) - { - //need to add some events! - if(!stage._interactiveEventsAdded) - { - stage._interactiveEventsAdded = true; - stage.interactionManager.setTarget(this); - } - } - - // after rendering lets confirm all frames that have been uodated.. - if(PIXI.Texture.frameUpdates.length > 0) - { - for (var i=0; i < PIXI.Texture.frameUpdates.length; i++) - { - PIXI.Texture.frameUpdates[i].updateFrame = false; - }; - - PIXI.Texture.frameUpdates = []; - } -} - -/** - * Updates the textures loaded into this webgl renderer - * - * @static - * @method updateTextures - * @private - */ -PIXI.WebGLRenderer.updateTextures = function() -{ - //TODO break this out into a texture manager... - for (var i=0; i < PIXI.texturesToUpdate.length; i++) PIXI.WebGLRenderer.updateTexture(PIXI.texturesToUpdate[i]); - for (var i=0; i < PIXI.texturesToDestroy.length; i++) PIXI.WebGLRenderer.destroyTexture(PIXI.texturesToDestroy[i]); - PIXI.texturesToUpdate = []; - PIXI.texturesToDestroy = []; -} - -/** - * Updates a loaded webgl texture - * - * @static - * @method updateTexture - * @param texture {Texture} The texture to update - * @private - */ -PIXI.WebGLRenderer.updateTexture = function(texture) -{ - //TODO break this out into a texture manager... - var gl = PIXI.gl; - - if(!texture._glTexture) - { - texture._glTexture = gl.createTexture(); - } - - if(texture.hasLoaded) - { - gl.bindTexture(gl.TEXTURE_2D, texture._glTexture); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true); - - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - - // reguler... - - if(!texture._powerOf2) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); - } - - gl.bindTexture(gl.TEXTURE_2D, null); - } -} - -/** - * Destroys a loaded webgl texture - * - * @method destroyTexture - * @param texture {Texture} The texture to update - * @private - */ -PIXI.WebGLRenderer.destroyTexture = function(texture) -{ - //TODO break this out into a texture manager... - var gl = PIXI.gl; - - if(texture._glTexture) - { - texture._glTexture = gl.createTexture(); - gl.deleteTexture(gl.TEXTURE_2D, texture._glTexture); - } -} - -/** - * resizes the webGL view to the specified width and height - * - * @method resize - * @param width {Number} the new width of the webGL view - * @param height {Number} the new height of the webGL view - */ -PIXI.WebGLRenderer.prototype.resize = function(width, height) -{ - this.width = width; - this.height = height; - - this.view.width = width; - this.view.height = height; - - this.gl.viewport(0, 0, this.width, this.height); - - //var projectionMatrix = this.projectionMatrix; - - PIXI.projection.x = this.width/2; - PIXI.projection.y = -this.height/2; - - //PIXI.size.x = this.width/2; - //PIXI.size.y = -this.height/2; - -// projectionMatrix[0] = 2/this.width; -// projectionMatrix[5] = -2/this.height; -// projectionMatrix[12] = -1; -// projectionMatrix[13] = 1; -} - -/** - * Handles a lost webgl context - * - * @method handleContextLost - * @param event {Event} - * @private - */ -PIXI.WebGLRenderer.prototype.handleContextLost = function(event) -{ - event.preventDefault(); - this.contextLost = true; -} - -/** - * Handles a restored webgl context - * - * @method handleContextRestored - * @param event {Event} - * @private - */ -PIXI.WebGLRenderer.prototype.handleContextRestored = function(event) -{ - this.gl = this.view.getContext("experimental-webgl", { - alpha: true - }); - - this.initShaders(); - - for(var key in PIXI.TextureCache) - { - var texture = PIXI.TextureCache[key].baseTexture; - texture._glTexture = null; - PIXI.WebGLRenderer.updateTexture(texture); - }; - - for (var i=0; i < this.batchs.length; i++) - { - this.batchs[i].restoreLostContext(this.gl)// - this.batchs[i].dirty = true; - }; - - PIXI._restoreBatchs(this.gl); - - this.contextLost = false; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * A WebGLBatch Enables a group of sprites to be drawn using the same settings. - * if a group of sprites all have the same baseTexture and blendMode then they can be - * grouped into a batch. All the sprites in a batch can then be drawn in one go by the - * GPU which is hugely efficient. ALL sprites in the webGL renderer are added to a batch - * even if the batch only contains one sprite. Batching is handled automatically by the - * webGL renderer. A good tip is: the smaller the number of batchs there are, the faster - * the webGL renderer will run. - * - * @class WebGLBatch - * @contructor - * @param gl {WebGLContext} An instance of the webGL context - */ -PIXI.WebGLRenderGroup = function(gl, transparent) -{ - this.gl = gl; - this.root; - - this.backgroundColor; - this.transparent = transparent == undefined ? true : transparent; - - this.batchs = []; - this.toRemove = []; - // console.log(this.transparent) - this.filterManager = new PIXI.WebGLFilterManager(this.transparent); -} - -// constructor -PIXI.WebGLRenderGroup.prototype.constructor = PIXI.WebGLRenderGroup; - -/** - * Add a display object to the webgl renderer - * - * @method setRenderable - * @param displayObject {DisplayObject} - * @private - */ -PIXI.WebGLRenderGroup.prototype.setRenderable = function(displayObject) -{ - // has this changed?? - if(this.root)this.removeDisplayObjectAndChildren(this.root); - - displayObject.worldVisible = displayObject.visible; - - // soooooo // - // to check if any batchs exist already?? - - // TODO what if its already has an object? should remove it - this.root = displayObject; - this.addDisplayObjectAndChildren(displayObject); -} - -/** - * Renders the stage to its webgl view - * - * @method render - * @param projection {Object} - */ -PIXI.WebGLRenderGroup.prototype.render = function(projection, buffer) -{ - PIXI.WebGLRenderer.updateTextures(); - - var gl = this.gl; - gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y); - - this.filterManager.begin(projection, buffer); - - - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - // will render all the elements in the group - var renderable; - - for (var i=0; i < this.batchs.length; i++) - { - - renderable = this.batchs[i]; - if(renderable instanceof PIXI.WebGLBatch) - { - this.batchs[i].render(); - continue; - } - - // render special - this.renderSpecial(renderable, projection); - } - -} - -/** - * Renders a specific displayObject - * - * @method renderSpecific - * @param displayObject {DisplayObject} - * @param projection {Object} - * @private - */ -PIXI.WebGLRenderGroup.prototype.renderSpecific = function(displayObject, projection, buffer) -{ - PIXI.WebGLRenderer.updateTextures(); - var gl = this.gl; - - gl.uniform2f(PIXI.defaultShader.projectionVector, projection.x, projection.y); - - this.filterManager.begin(projection, buffer); - - // to do! - // render part of the scene... - - var startIndex; - var startBatchIndex; - - var endIndex; - var endBatchIndex; - - /* - * LOOK FOR THE NEXT SPRITE - * This part looks for the closest next sprite that can go into a batch - * it keeps looking until it finds a sprite or gets to the end of the display - * scene graph - */ - var nextRenderable = displayObject.first; - while(nextRenderable._iNext) - { - if(nextRenderable.renderable && nextRenderable.__renderGroup)break; - nextRenderable = nextRenderable._iNext; - } - var startBatch = nextRenderable.batch; - //console.log(nextRenderable); - - //console.log(renderable) - if(nextRenderable instanceof PIXI.Sprite) - { - startBatch = nextRenderable.batch; - - var head = startBatch.head; - var next = head; - - // ok now we have the batch.. need to find the start index! - if(head == nextRenderable) - { - startIndex = 0; - } - else - { - startIndex = 1; - - while(head.__next != nextRenderable) - { - startIndex++; - head = head.__next; - } - } - } - else - { - startBatch = nextRenderable; - } - - // Get the LAST renderable object - var lastRenderable = displayObject.last; - while(lastRenderable._iPrev) - { - if(lastRenderable.renderable && lastRenderable.__renderGroup)break; - lastRenderable = lastRenderable._iNext; - } - - if(lastRenderable instanceof PIXI.Sprite) - { - endBatch = lastRenderable.batch; - - var head = endBatch.head; - - if(head == lastRenderable) - { - endIndex = 0; - } - else - { - endIndex = 1; - - while(head.__next != lastRenderable) - { - endIndex++; - head = head.__next; - } - } - } - else - { - endBatch = lastRenderable; - } - - //console.log(endBatch); - // TODO - need to fold this up a bit! - - if(startBatch == endBatch) - { - if(startBatch instanceof PIXI.WebGLBatch) - { - startBatch.render(startIndex, endIndex+1); - } - else - { - this.renderSpecial(startBatch, projection); - } - return; - } - - // now we have first and last! - startBatchIndex = this.batchs.indexOf(startBatch); - endBatchIndex = this.batchs.indexOf(endBatch); - - // DO the first batch - if(startBatch instanceof PIXI.WebGLBatch) - { - startBatch.render(startIndex); - } - else - { - this.renderSpecial(startBatch, projection); - } - - // DO the middle batchs.. - for (var i=startBatchIndex+1; i < endBatchIndex; i++) - { - renderable = this.batchs[i]; - - if(renderable instanceof PIXI.WebGLBatch) - { - this.batchs[i].render(); - } - else - { - this.renderSpecial(renderable, projection); - } - } - - // DO the last batch.. - if(endBatch instanceof PIXI.WebGLBatch) - { - endBatch.render(0, endIndex+1); - } - else - { - this.renderSpecial(endBatch, projection); - } -} - -/** - * Renders a specific renderable - * - * @method renderSpecial - * @param renderable {DisplayObject} - * @param projection {Object} - * @private - */ -PIXI.WebGLRenderGroup.prototype.renderSpecial = function(renderable, projection) -{ - - var worldVisible = renderable.vcount === PIXI.visibleCount - - - if(renderable instanceof PIXI.TilingSprite) - { - if(worldVisible)this.renderTilingSprite(renderable, projection); - } - else if(renderable instanceof PIXI.Strip) - { - if(worldVisible)this.renderStrip(renderable, projection); - } - else if(renderable instanceof PIXI.CustomRenderable) - { - if(worldVisible) renderable.renderWebGL(this, projection); - } - else if(renderable instanceof PIXI.Graphics) - { - if(worldVisible && renderable.renderable) PIXI.WebGLGraphics.renderGraphics(renderable, projection); - } - else if(renderable instanceof PIXI.FilterBlock) - { - this.handleFilterBlock(renderable, projection); - } -} - -flip = false; -var maskStack = []; -var maskPosition = 0; - -//var usedMaskStack = []; - -PIXI.WebGLRenderGroup.prototype.handleFilterBlock = function(filterBlock, projection) -{ - /* - * for now only masks are supported.. - */ - var gl = PIXI.gl; - - if(filterBlock.open) - { - if(filterBlock.data instanceof Array) - { - this.filterManager.pushFilter(filterBlock); - // ok so.. - - } - else - { - maskPosition++; - - maskStack.push(filterBlock) - - gl.enable(gl.STENCIL_TEST); - - gl.colorMask(false, false, false, false); - - gl.stencilFunc(gl.ALWAYS,1,1); - gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR); - - PIXI.WebGLGraphics.renderGraphics(filterBlock.data, projection); - - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length); - gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); - } - } - else - { - if(filterBlock.data instanceof Array) - { - this.filterManager.popFilter(); - } - else - { - var maskData = maskStack.pop(filterBlock) - - - if(maskData) - { - gl.colorMask(false, false, false, false); - - gl.stencilFunc(gl.ALWAYS,1,1); - gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR); - - PIXI.WebGLGraphics.renderGraphics(maskData.data, projection); - - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.NOTEQUAL,0,maskStack.length); - gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP); - }; - - gl.disable(gl.STENCIL_TEST); - } - } -} - -/** - * Updates a webgl texture - * - * @method updateTexture - * @param displayObject {DisplayObject} - * @private - */ -PIXI.WebGLRenderGroup.prototype.updateTexture = function(displayObject) -{ - - // TODO definitely can optimse this function.. - - this.removeObject(displayObject); - - /* - * LOOK FOR THE PREVIOUS RENDERABLE - * This part looks for the closest previous sprite that can go into a batch - * It keeps going back until it finds a sprite or the stage - */ - var previousRenderable = displayObject.first; - while(previousRenderable != this.root) - { - previousRenderable = previousRenderable._iPrev; - if(previousRenderable.renderable && previousRenderable.__renderGroup)break; - } - - /* - * LOOK FOR THE NEXT SPRITE - * This part looks for the closest next sprite that can go into a batch - * it keeps looking until it finds a sprite or gets to the end of the display - * scene graph - */ - var nextRenderable = displayObject.last; - while(nextRenderable._iNext) - { - nextRenderable = nextRenderable._iNext; - if(nextRenderable.renderable && nextRenderable.__renderGroup)break; - } - - this.insertObject(displayObject, previousRenderable, nextRenderable); -} - -/** - * Adds filter blocks - * - * @method addFilterBlocks - * @param start {FilterBlock} - * @param end {FilterBlock} - * @private - */ -PIXI.WebGLRenderGroup.prototype.addFilterBlocks = function(start, end) -{ - start.__renderGroup = this; - end.__renderGroup = this; - /* - * LOOK FOR THE PREVIOUS RENDERABLE - * This part looks for the closest previous sprite that can go into a batch - * It keeps going back until it finds a sprite or the stage - */ - var previousRenderable = start; - while(previousRenderable != this.root.first) - { - previousRenderable = previousRenderable._iPrev; - if(previousRenderable.renderable && previousRenderable.__renderGroup)break; - } - this.insertAfter(start, previousRenderable); - - /* - * LOOK FOR THE NEXT SPRITE - * This part looks for the closest next sprite that can go into a batch - * it keeps looking until it finds a sprite or gets to the end of the display - * scene graph - */ - var previousRenderable2 = end; - while(previousRenderable2 != this.root.first) - { - previousRenderable2 = previousRenderable2._iPrev; - if(previousRenderable2.renderable && previousRenderable2.__renderGroup)break; - } - this.insertAfter(end, previousRenderable2); -} - -/** - * Remove filter blocks - * - * @method removeFilterBlocks - * @param start {FilterBlock} - * @param end {FilterBlock} - * @private - */ -PIXI.WebGLRenderGroup.prototype.removeFilterBlocks = function(start, end) -{ - this.removeObject(start); - this.removeObject(end); -} - -/** - * Adds a display object and children to the webgl context - * - * @method addDisplayObjectAndChildren - * @param displayObject {DisplayObject} - * @private - */ -PIXI.WebGLRenderGroup.prototype.addDisplayObjectAndChildren = function(displayObject) -{ - if(displayObject.__renderGroup)displayObject.__renderGroup.removeDisplayObjectAndChildren(displayObject); - - /* - * LOOK FOR THE PREVIOUS RENDERABLE - * This part looks for the closest previous sprite that can go into a batch - * It keeps going back until it finds a sprite or the stage - */ - - var previousRenderable = displayObject.first; - while(previousRenderable != this.root.first) - { - previousRenderable = previousRenderable._iPrev; - if(previousRenderable.renderable && previousRenderable.__renderGroup)break; - } - - /* - * LOOK FOR THE NEXT SPRITE - * This part looks for the closest next sprite that can go into a batch - * it keeps looking until it finds a sprite or gets to the end of the display - * scene graph - */ - var nextRenderable = displayObject.last; - while(nextRenderable._iNext) - { - nextRenderable = nextRenderable._iNext; - if(nextRenderable.renderable && nextRenderable.__renderGroup)break; - } - - // one the display object hits this. we can break the loop - - var tempObject = displayObject.first; - var testObject = displayObject.last._iNext; - do - { - tempObject.__renderGroup = this; - - if(tempObject.renderable) - { - - this.insertObject(tempObject, previousRenderable, nextRenderable); - previousRenderable = tempObject; - } - - tempObject = tempObject._iNext; - } - while(tempObject != testObject) -} - -/** - * Removes a display object and children to the webgl context - * - * @method removeDisplayObjectAndChildren - * @param displayObject {DisplayObject} - * @private - */ -PIXI.WebGLRenderGroup.prototype.removeDisplayObjectAndChildren = function(displayObject) -{ - if(displayObject.__renderGroup != this)return; - -// var displayObject = displayObject.first; - var lastObject = displayObject.last; - do - { - displayObject.__renderGroup = null; - if(displayObject.renderable)this.removeObject(displayObject); - displayObject = displayObject._iNext; - } - while(displayObject) -} - -/** - * Inserts a displayObject into the linked list - * - * @method insertObject - * @param displayObject {DisplayObject} - * @param previousObject {DisplayObject} - * @param nextObject {DisplayObject} - * @private - */ -PIXI.WebGLRenderGroup.prototype.insertObject = function(displayObject, previousObject, nextObject) -{ - // while looping below THE OBJECT MAY NOT HAVE BEEN ADDED - var previousSprite = previousObject; - var nextSprite = nextObject; - - /* - * so now we have the next renderable and the previous renderable - * - */ - if(displayObject instanceof PIXI.Sprite) - { - var previousBatch - var nextBatch - - if(previousSprite instanceof PIXI.Sprite) - { - previousBatch = previousSprite.batch; - if(previousBatch) - { - if(previousBatch.texture == displayObject.texture.baseTexture && previousBatch.blendMode == displayObject.blendMode) - { - previousBatch.insertAfter(displayObject, previousSprite); - return; - } - } - } - else - { - // TODO reword! - previousBatch = previousSprite; - } - - if(nextSprite) - { - if(nextSprite instanceof PIXI.Sprite) - { - nextBatch = nextSprite.batch; - - //batch may not exist if item was added to the display list but not to the webGL - if(nextBatch) - { - if(nextBatch.texture == displayObject.texture.baseTexture && nextBatch.blendMode == displayObject.blendMode) - { - nextBatch.insertBefore(displayObject, nextSprite); - return; - } - else - { - if(nextBatch == previousBatch) - { - // THERE IS A SPLIT IN THIS BATCH! // - var splitBatch = previousBatch.split(nextSprite); - // COOL! - // add it back into the array - /* - * OOPS! - * seems the new sprite is in the middle of a batch - * lets split it.. - */ - var batch = PIXI.WebGLRenderer.getBatch(); - - var index = this.batchs.indexOf( previousBatch ); - batch.init(displayObject); - this.batchs.splice(index+1, 0, batch, splitBatch); - - return; - } - } - } - } - else - { - // TODO re-word! - - nextBatch = nextSprite; - } - } - - /* - * looks like it does not belong to any batch! - * but is also not intersecting one.. - * time to create anew one! - */ - - var batch = PIXI.WebGLRenderer.getBatch(); - batch.init(displayObject); - - if(previousBatch) // if this is invalid it means - { - var index = this.batchs.indexOf( previousBatch ); - this.batchs.splice(index+1, 0, batch); - } - else - { - this.batchs.push(batch); - } - - return; - } - else if(displayObject instanceof PIXI.TilingSprite) - { - - // add to a batch!! - this.initTilingSprite(displayObject); - // this.batchs.push(displayObject); - - } - else if(displayObject instanceof PIXI.Strip) - { - // add to a batch!! - this.initStrip(displayObject); - // this.batchs.push(displayObject); - } - else if(displayObject)// instanceof PIXI.Graphics) - { - //displayObject.initWebGL(this); - - // add to a batch!! - //this.initStrip(displayObject); - //this.batchs.push(displayObject); - } - - this.insertAfter(displayObject, previousSprite); - - // insert and SPLIT! - -} - -/** - * Inserts a displayObject into the linked list - * - * @method insertAfter - * @param item {DisplayObject} - * @param displayObject {DisplayObject} The object to insert - * @private - */ -PIXI.WebGLRenderGroup.prototype.insertAfter = function(item, displayObject) -{ - if(displayObject instanceof PIXI.Sprite) - { - var previousBatch = displayObject.batch; - - if(previousBatch) - { - // so this object is in a batch! - - // is it not? need to split the batch - if(previousBatch.tail == displayObject) - { - // is it tail? insert in to batchs - var index = this.batchs.indexOf( previousBatch ); - this.batchs.splice(index+1, 0, item); - } - else - { - // TODO MODIFY ADD / REMOVE CHILD TO ACCOUNT FOR FILTERS (also get prev and next) // - - // THERE IS A SPLIT IN THIS BATCH! // - var splitBatch = previousBatch.split(displayObject.__next); - - // COOL! - // add it back into the array - /* - * OOPS! - * seems the new sprite is in the middle of a batch - * lets split it.. - */ - var index = this.batchs.indexOf( previousBatch ); - this.batchs.splice(index+1, 0, item, splitBatch); - } - } - else - { - this.batchs.push(item); - } - } - else - { - var index = this.batchs.indexOf( displayObject ); - this.batchs.splice(index+1, 0, item); - } -} - -/** - * Removes a displayObject from the linked list - * - * @method removeObject - * @param displayObject {DisplayObject} The object to remove - * @private - */ -PIXI.WebGLRenderGroup.prototype.removeObject = function(displayObject) -{ - // loop through children.. - // display object // - - // add a child from the render group.. - // remove it and all its children! - //displayObject.cacheVisible = false;//displayObject.visible; - - /* - * removing is a lot quicker.. - * - */ - var batchToRemove; - - if(displayObject instanceof PIXI.Sprite) - { - // should always have a batch! - var batch = displayObject.batch; - if(!batch)return; // this means the display list has been altered befre rendering - - batch.remove(displayObject); - - if(batch.size==0) - { - batchToRemove = batch; - } - } - else - { - batchToRemove = displayObject; - } - - /* - * Looks like there is somthing that needs removing! - */ - if(batchToRemove) - { - var index = this.batchs.indexOf( batchToRemove ); - if(index == -1)return;// this means it was added then removed before rendered - - // ok so.. check to see if you adjacent batchs should be joined. - // TODO may optimise? - if(index == 0 || index == this.batchs.length-1) - { - // wha - eva! just get of the empty batch! - this.batchs.splice(index, 1); - if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove); - - return; - } - - if(this.batchs[index-1] instanceof PIXI.WebGLBatch && this.batchs[index+1] instanceof PIXI.WebGLBatch) - { - if(this.batchs[index-1].texture == this.batchs[index+1].texture && this.batchs[index-1].blendMode == this.batchs[index+1].blendMode) - { - //console.log("MERGE") - this.batchs[index-1].merge(this.batchs[index+1]); - - if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove); - PIXI.WebGLRenderer.returnBatch(this.batchs[index+1]); - this.batchs.splice(index, 2); - return; - } - } - - this.batchs.splice(index, 1); - if(batchToRemove instanceof PIXI.WebGLBatch)PIXI.WebGLRenderer.returnBatch(batchToRemove); - } -} - - -/** - * Initializes a tiling sprite - * - * @method initTilingSprite - * @param sprite {TilingSprite} The tiling sprite to initialize - * @private - */ -PIXI.WebGLRenderGroup.prototype.initTilingSprite = function(sprite) -{ - var gl = this.gl; - - // make the texture tilable.. - - sprite.verticies = new Float32Array([0, 0, - sprite.width, 0, - sprite.width, sprite.height, - 0, sprite.height]); - - sprite.uvs = new Float32Array([0, 0, - 1, 0, - 1, 1, - 0, 1]); - - sprite.colors = new Float32Array([1,1,1,1]); - - sprite.indices = new Uint16Array([0, 1, 3,2])//, 2]); - - sprite._vertexBuffer = gl.createBuffer(); - sprite._indexBuffer = gl.createBuffer(); - sprite._uvBuffer = gl.createBuffer(); - sprite._colorBuffer = gl.createBuffer(); - - gl.bindBuffer(gl.ARRAY_BUFFER, sprite._vertexBuffer); - gl.bufferData(gl.ARRAY_BUFFER, sprite.verticies, gl.STATIC_DRAW); - - gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer); - gl.bufferData(gl.ARRAY_BUFFER, sprite.uvs, gl.DYNAMIC_DRAW); - - gl.bindBuffer(gl.ARRAY_BUFFER, sprite._colorBuffer); - gl.bufferData(gl.ARRAY_BUFFER, sprite.colors, gl.STATIC_DRAW); - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, sprite._indexBuffer); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, sprite.indices, gl.STATIC_DRAW); - -// return ( (x > 0) && ((x & (x - 1)) == 0) ); - - if(sprite.texture.baseTexture._glTexture) - { - gl.bindTexture(gl.TEXTURE_2D, sprite.texture.baseTexture._glTexture); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); - sprite.texture.baseTexture._powerOf2 = true; - } - else - { - sprite.texture.baseTexture._powerOf2 = true; - } -} - -/** - * Renders a Strip - * - * @method renderStrip - * @param strip {Strip} The strip to render - * @param projection {Object} - * @private - */ -PIXI.WebGLRenderGroup.prototype.renderStrip = function(strip, projection) -{ - var gl = this.gl; - - PIXI.activateStripShader(); - - var shader = PIXI.stripShader; - - var program = shader.program; - - var m = PIXI.mat3.clone(strip.worldTransform); - - PIXI.mat3.transpose(m); - -// console.log(projection) - // set the matrix transform for the - gl.uniformMatrix3fv(shader.translationMatrix, false, m); - gl.uniform2f(shader.projectionVector, projection.x, projection.y); - gl.uniform2f(shader.offsetVector, -PIXI.offset.x, -PIXI.offset.y); - - gl.uniform1f(shader.alpha, strip.worldAlpha); - - /* - if(strip.blendMode == PIXI.blendModes.NORMAL) - { - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); - } - else - { - gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_COLOR); - } - */ - - //console.log("!!") - if(!strip.dirty) - { - gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); - gl.bufferSubData(gl.ARRAY_BUFFER, 0, strip.verticies) - gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); - - // update the uvs - gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); - gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture); - - gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); - gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0); - - // dont need to upload! - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); - } - else - { - strip.dirty = false; - gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); - gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.STATIC_DRAW) - gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0); - - // update the uvs - gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); - gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW) - gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0); - - gl.activeTexture(gl.TEXTURE0); - gl.bindTexture(gl.TEXTURE_2D, strip.texture.baseTexture._glTexture); - // console.log(strip.texture.baseTexture._glTexture) - gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); - gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW) - gl.vertexAttribPointer(shader.colorAttribute, 1, gl.FLOAT, false, 0, 0); - - // dont need to upload! - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW); - - } - - gl.drawElements(gl.TRIANGLE_STRIP, strip.indices.length, gl.UNSIGNED_SHORT, 0); - - PIXI.deactivateStripShader(); - //gl.useProgram(PIXI.currentProgram); -} - -/** - * Renders a TilingSprite - * - * @method renderTilingSprite - * @param sprite {TilingSprite} The tiling sprite to render - * @param projectionMatrix {Object} - * @private - */ -PIXI.WebGLRenderGroup.prototype.renderTilingSprite = function(sprite, projectionMatrix) -{ - var gl = this.gl; - - - var shaderProgram = PIXI.shaderProgram; - - var tilePosition = sprite.tilePosition; - var tileScale = sprite.tileScale; - - var offsetX = tilePosition.x/sprite.texture.baseTexture.width; - var offsetY = tilePosition.y/sprite.texture.baseTexture.height; - - var scaleX = (sprite.width / sprite.texture.baseTexture.width) / tileScale.x; - var scaleY = (sprite.height / sprite.texture.baseTexture.height) / tileScale.y; - - sprite.uvs[0] = 0 - offsetX; - sprite.uvs[1] = 0 - offsetY; - - sprite.uvs[2] = (1 * scaleX) -offsetX; - sprite.uvs[3] = 0 - offsetY; - - sprite.uvs[4] = (1 *scaleX) - offsetX; - sprite.uvs[5] = (1 *scaleY) - offsetY; - - sprite.uvs[6] = 0 - offsetX; - sprite.uvs[7] = (1 *scaleY) - offsetY; - - gl.bindBuffer(gl.ARRAY_BUFFER, sprite._uvBuffer); - gl.bufferSubData(gl.ARRAY_BUFFER, 0, sprite.uvs) - - this.renderStrip(sprite, projectionMatrix); -} - -/** - * Initializes a strip to be rendered - * - * @method initStrip - * @param strip {Strip} The strip to initialize - * @private - */ -PIXI.WebGLRenderGroup.prototype.initStrip = function(strip) -{ - // build the strip! - var gl = this.gl; - var shaderProgram = this.shaderProgram; - - strip._vertexBuffer = gl.createBuffer(); - strip._indexBuffer = gl.createBuffer(); - strip._uvBuffer = gl.createBuffer(); - strip._colorBuffer = gl.createBuffer(); - - gl.bindBuffer(gl.ARRAY_BUFFER, strip._vertexBuffer); - gl.bufferData(gl.ARRAY_BUFFER, strip.verticies, gl.DYNAMIC_DRAW); - - gl.bindBuffer(gl.ARRAY_BUFFER, strip._uvBuffer); - gl.bufferData(gl.ARRAY_BUFFER, strip.uvs, gl.STATIC_DRAW); - - gl.bindBuffer(gl.ARRAY_BUFFER, strip._colorBuffer); - gl.bufferData(gl.ARRAY_BUFFER, strip.colors, gl.STATIC_DRAW); - - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, strip._indexBuffer); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, strip.indices, gl.STATIC_DRAW); -} - - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - - -PIXI.initDefaultShaders = function() -{ - PIXI.primitiveShader = new PIXI.PrimitiveShader(); - PIXI.primitiveShader.init(); - - PIXI.stripShader = new PIXI.StripShader(); - PIXI.stripShader.init(); - - PIXI.defaultShader = new PIXI.PixiShader(); - PIXI.defaultShader.init(); - - var gl = PIXI.gl; - var shaderProgram = PIXI.defaultShader.program; - - - gl.useProgram(shaderProgram); - - gl.enableVertexAttribArray(PIXI.defaultShader.aVertexPosition); - gl.enableVertexAttribArray(PIXI.defaultShader.colorAttribute); - gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord); -} - -PIXI.activatePrimitiveShader = function() -{ - var gl = PIXI.gl; - - gl.useProgram(PIXI.primitiveShader.program); - - gl.disableVertexAttribArray(PIXI.defaultShader.aVertexPosition); - gl.disableVertexAttribArray(PIXI.defaultShader.colorAttribute); - gl.disableVertexAttribArray(PIXI.defaultShader.aTextureCoord); - - gl.enableVertexAttribArray(PIXI.primitiveShader.aVertexPosition); - gl.enableVertexAttribArray(PIXI.primitiveShader.colorAttribute); -} - -PIXI.deactivatePrimitiveShader = function() -{ - var gl = PIXI.gl; - - gl.useProgram(PIXI.defaultShader.program); - - gl.disableVertexAttribArray(PIXI.primitiveShader.aVertexPosition); - gl.disableVertexAttribArray(PIXI.primitiveShader.colorAttribute); - - gl.enableVertexAttribArray(PIXI.defaultShader.aVertexPosition); - gl.enableVertexAttribArray(PIXI.defaultShader.colorAttribute); - gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord); - -} - -PIXI.activateStripShader = function() -{ - var gl = PIXI.gl; - - gl.useProgram(PIXI.stripShader.program); - // gl.disableVertexAttribArray(PIXI.defaultShader.aTextureCoord); -} - -PIXI.deactivateStripShader = function() -{ - var gl = PIXI.gl; - - gl.useProgram(PIXI.defaultShader.program); - //gl.enableVertexAttribArray(PIXI.defaultShader.aTextureCoord); -} - -/* - -SHADER COMPILER HELPERS -*/ - -PIXI.CompileVertexShader = function(gl, shaderSrc) -{ - return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER); -} - -PIXI.CompileFragmentShader = function(gl, shaderSrc) -{ - return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER); -} - -PIXI._CompileShader = function(gl, shaderSrc, shaderType) -{ - var src = shaderSrc.join("\n"); - var shader = gl.createShader(shaderType); - gl.shaderSource(shader, src); - gl.compileShader(shader); - - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); - return null; - } - - return shader; -} - - -PIXI.compileProgram = function(vertexSrc, fragmentSrc) -{ - var gl = PIXI.gl; - var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc); - var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc); - - var shaderProgram = gl.createProgram(); - - gl.attachShader(shaderProgram, vertexShader); - gl.attachShader(shaderProgram, fragmentShader); - gl.linkProgram(shaderProgram); - - if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { - console.log("Could not initialise shaders"); - } - - return shaderProgram; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * A Text Object will create a line(s) of text using bitmap font. To split a line you can use "\n", "\r" or "\r\n" - * You can generate the fnt files using - * http://www.angelcode.com/products/bmfont/ for windows or - * http://www.bmglyph.com/ for mac. - * - * @class BitmapText - * @extends DisplayObjectContainer - * @constructor - * @param text {String} The copy that you would like the text to display - * @param style {Object} The style parameters - * @param style.font {String} The size (optional) and bitmap font id (required) eq "Arial" or "20px Arial" (must have loaded previously) - * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right") - */ -PIXI.BitmapText = function(text, style) -{ - PIXI.DisplayObjectContainer.call(this); - - this.setText(text); - this.setStyle(style); - this.updateText(); - this.dirty = false - -}; - -// constructor -PIXI.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype); -PIXI.BitmapText.prototype.constructor = PIXI.BitmapText; - -/** - * Set the copy for the text object - * - * @method setText - * @param text {String} The copy that you would like the text to display - */ -PIXI.BitmapText.prototype.setText = function(text) -{ - this.text = text || " "; - this.dirty = true; -}; - -/** - * Set the style of the text - * - * @method setStyle - * @param style {Object} The style parameters - * @param style.font {String} The size (optional) and bitmap font id (required) eq "Arial" or "20px Arial" (must have loaded previously) - * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right") - */ -PIXI.BitmapText.prototype.setStyle = function(style) -{ - style = style || {}; - style.align = style.align || "left"; - this.style = style; - - var font = style.font.split(" "); - this.fontName = font[font.length - 1]; - this.fontSize = font.length >= 2 ? parseInt(font[font.length - 2], 10) : PIXI.BitmapText.fonts[this.fontName].size; - - this.dirty = true; -}; - -/** - * Renders text - * - * @method updateText - * @private - */ -PIXI.BitmapText.prototype.updateText = function() -{ - var data = PIXI.BitmapText.fonts[this.fontName]; - var pos = new PIXI.Point(); - var prevCharCode = null; - var chars = []; - var maxLineWidth = 0; - var lineWidths = []; - var line = 0; - var scale = this.fontSize / data.size; - for(var i = 0; i < this.text.length; i++) - { - var charCode = this.text.charCodeAt(i); - if(/(?:\r\n|\r|\n)/.test(this.text.charAt(i))) - { - lineWidths.push(pos.x); - maxLineWidth = Math.max(maxLineWidth, pos.x); - line++; - - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } - - var charData = data.chars[charCode]; - if(!charData) continue; - - if(prevCharCode && charData[prevCharCode]) - { - pos.x += charData.kerning[prevCharCode]; - } - chars.push({texture:charData.texture, line: line, charCode: charCode, position: new PIXI.Point(pos.x + charData.xOffset, pos.y + charData.yOffset)}); - pos.x += charData.xAdvance; - - prevCharCode = charCode; - } - - lineWidths.push(pos.x); - maxLineWidth = Math.max(maxLineWidth, pos.x); - - var lineAlignOffsets = []; - for(i = 0; i <= line; i++) - { - var alignOffset = 0; - if(this.style.align == "right") - { - alignOffset = maxLineWidth - lineWidths[i]; - } - else if(this.style.align == "center") - { - alignOffset = (maxLineWidth - lineWidths[i]) / 2; - } - lineAlignOffsets.push(alignOffset); - } - - for(i = 0; i < chars.length; i++) - { - var c = new PIXI.Sprite(chars[i].texture)//PIXI.Sprite.fromFrame(chars[i].charCode); - c.position.x = (chars[i].position.x + lineAlignOffsets[chars[i].line]) * scale; - c.position.y = chars[i].position.y * scale; - c.scale.x = c.scale.y = scale; - this.addChild(c); - } - - this.width = pos.x * scale; - this.height = (pos.y + data.lineHeight) * scale; -}; - -/** - * Updates the transfor of this object - * - * @method updateTransform - * @private - */ -PIXI.BitmapText.prototype.updateTransform = function() -{ - if(this.dirty) - { - while(this.children.length > 0) - { - this.removeChild(this.getChildAt(0)); - } - this.updateText(); - - this.dirty = false; - } - - PIXI.DisplayObjectContainer.prototype.updateTransform.call(this); -}; - -PIXI.BitmapText.fonts = {}; - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - * A Text Object will create a line(s) of text to split a line you can use "\n" - * - * @class Text - * @extends Sprite - * @constructor - * @param text {String} The copy that you would like the text to display - * @param [style] {Object} The style parameters - * @param [style.font] {String} default "bold 20pt Arial" The style and size of the font - * @param [style.fill="black"] {Object} A canvas fillstyle that will be used on the text eg "red", "#00FF00" - * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right") - * @param [style.stroke] {String} A canvas fillstyle that will be used on the text stroke eg "blue", "#FCFF00" - * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke) - * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used - * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap - */ -PIXI.Text = function(text, style) -{ - this.canvas = document.createElement("canvas"); - this.context = this.canvas.getContext("2d"); - PIXI.Sprite.call(this, PIXI.Texture.fromCanvas(this.canvas)); - - this.setText(text); - this.setStyle(style); - - this.updateText(); - this.dirty = false; -}; - -// constructor -PIXI.Text.prototype = Object.create(PIXI.Sprite.prototype); -PIXI.Text.prototype.constructor = PIXI.Text; - -/** - * Set the style of the text - * - * @method setStyle - * @param [style] {Object} The style parameters - * @param [style.font="bold 20pt Arial"] {String} The style and size of the font - * @param [style.fill="black"] {Object} A canvas fillstyle that will be used on the text eg "red", "#00FF00" - * @param [style.align="left"] {String} An alignment of the multiline text ("left", "center" or "right") - * @param [style.stroke="black"] {String} A canvas fillstyle that will be used on the text stroke eg "blue", "#FCFF00" - * @param [style.strokeThickness=0] {Number} A number that represents the thickness of the stroke. Default is 0 (no stroke) - * @param [style.wordWrap=false] {Boolean} Indicates if word wrap should be used - * @param [style.wordWrapWidth=100] {Number} The width at which text will wrap - */ -PIXI.Text.prototype.setStyle = function(style) -{ - style = style || {}; - style.font = style.font || "bold 20pt Arial"; - style.fill = style.fill || "black"; - style.align = style.align || "left"; - style.stroke = style.stroke || "black"; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136 - style.strokeThickness = style.strokeThickness || 0; - style.wordWrap = style.wordWrap || false; - style.wordWrapWidth = style.wordWrapWidth || 100; - this.style = style; - this.dirty = true; -}; - -/** - * Set the copy for the text object. To split a line you can use "\n" - * - * @methos setText - * @param {String} text The copy that you would like the text to display - */ -PIXI.Text.prototype.setText = function(text) -{ - this.text = text.toString() || " "; - this.dirty = true; -}; - -/** - * Renders text - * - * @method updateText - * @private - */ -PIXI.Text.prototype.updateText = function() -{ - this.context.font = this.style.font; - - var outputText = this.text; - - // word wrap - // preserve original text - if(this.style.wordWrap)outputText = this.wordWrap(this.text); - - //split text into lines - var lines = outputText.split(/(?:\r\n|\r|\n)/); - - //calculate text width - var lineWidths = []; - var maxLineWidth = 0; - for (var i = 0; i < lines.length; i++) - { - var lineWidth = this.context.measureText(lines[i]).width; - lineWidths[i] = lineWidth; - maxLineWidth = Math.max(maxLineWidth, lineWidth); - } - this.canvas.width = maxLineWidth + this.style.strokeThickness; - - //calculate text height - var lineHeight = this.determineFontHeight("font: " + this.style.font + ";") + this.style.strokeThickness; - this.canvas.height = lineHeight * lines.length; - - //set canvas text styles - this.context.fillStyle = this.style.fill; - this.context.font = this.style.font; - - this.context.strokeStyle = this.style.stroke; - this.context.lineWidth = this.style.strokeThickness; - - this.context.textBaseline = "top"; - - //draw lines line by line - for (i = 0; i < lines.length; i++) - { - var linePosition = new PIXI.Point(this.style.strokeThickness / 2, this.style.strokeThickness / 2 + i * lineHeight); - - if(this.style.align == "right") - { - linePosition.x += maxLineWidth - lineWidths[i]; - } - else if(this.style.align == "center") - { - linePosition.x += (maxLineWidth - lineWidths[i]) / 2; - } - - if(this.style.stroke && this.style.strokeThickness) - { - this.context.strokeText(lines[i], linePosition.x, linePosition.y); - } - - if(this.style.fill) - { - this.context.fillText(lines[i], linePosition.x, linePosition.y); - } - } - - this.updateTexture(); -}; - -/** - * Updates texture size based on canvas size - * - * @method updateTexture - * @private - */ -PIXI.Text.prototype.updateTexture = function() -{ - this.texture.baseTexture.width = this.canvas.width; - this.texture.baseTexture.height = this.canvas.height; - this.texture.frame.width = this.canvas.width; - this.texture.frame.height = this.canvas.height; - - this._width = this.canvas.width; - this._height = this.canvas.height; - - PIXI.texturesToUpdate.push(this.texture.baseTexture); -}; - -/** - * Updates the transfor of this object - * - * @method updateTransform - * @private - */ -PIXI.Text.prototype.updateTransform = function() -{ - if(this.dirty) - { - this.updateText(); - this.dirty = false; - } - - PIXI.Sprite.prototype.updateTransform.call(this); -}; - -/* - * http://stackoverflow.com/users/34441/ellisbben - * great solution to the problem! - * - * @method determineFontHeight - * @param fontStyle {Object} - * @private - */ -PIXI.Text.prototype.determineFontHeight = function(fontStyle) -{ - // build a little reference dictionary so if the font style has been used return a - // cached version... - var result = PIXI.Text.heightCache[fontStyle]; - - if(!result) - { - var body = document.getElementsByTagName("body")[0]; - var dummy = document.createElement("div"); - var dummyText = document.createTextNode("M"); - dummy.appendChild(dummyText); - dummy.setAttribute("style", fontStyle + ';position:absolute;top:0;left:0'); - body.appendChild(dummy); - - result = dummy.offsetHeight; - PIXI.Text.heightCache[fontStyle] = result; - - body.removeChild(dummy); - } - - return result; -}; - -/** - * Applies newlines to a string to have it optimally fit into the horizontal - * bounds set by the Text object's wordWrapWidth property. - * - * @method wordWrap - * @param text {String} - * @private - */ -PIXI.Text.prototype.wordWrap = function(text) -{ - // Greedy wrapping algorithm that will wrap words as the line grows longer - // than its horizontal bounds. - var result = ""; - var lines = text.split("\n"); - for (var i = 0; i < lines.length; i++) - { - var spaceLeft = this.style.wordWrapWidth; - var words = lines[i].split(" "); - for (var j = 0; j < words.length; j++) - { - var wordWidth = this.context.measureText(words[j]).width; - var wordWidthWithSpace = wordWidth + this.context.measureText(" ").width; - if(wordWidthWithSpace > spaceLeft) - { - // Skip printing the newline if it's the first word of the line that is - // greater than the word wrap width. - if(j > 0) - { - result += "\n"; - } - result += words[j] + " "; - spaceLeft = this.style.wordWrapWidth - wordWidth; - } - else - { - spaceLeft -= wordWidthWithSpace; - result += words[j] + " "; - } - } - result += "\n"; - } - return result; -}; - -/** - * Destroys this text object - * - * @method destroy - * @param destroyTexture {Boolean} - */ -PIXI.Text.prototype.destroy = function(destroyTexture) -{ - if(destroyTexture) - { - this.texture.destroy(); - } - -}; - -PIXI.Text.heightCache = {}; - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -PIXI.BaseTextureCache = {}; -PIXI.texturesToUpdate = []; -PIXI.texturesToDestroy = []; - -/** - * A texture stores the information that represents an image. All textures have a base texture - * - * @class BaseTexture - * @uses EventTarget - * @constructor - * @param source {String} the source object (image or canvas) - */ -PIXI.BaseTexture = function(source) -{ - PIXI.EventTarget.call( this ); - - /** - * [read-only] The width of the base texture set when the image has loaded - * - * @property width - * @type Number - * @readOnly - */ - this.width = 100; - - /** - * [read-only] The height of the base texture set when the image has loaded - * - * @property height - * @type Number - * @readOnly - */ - this.height = 100; - - /** - * [read-only] Describes if the base texture has loaded or not - * - * @property hasLoaded - * @type Boolean - * @readOnly - */ - this.hasLoaded = false; - - /** - * The source that is loaded to create the texture - * - * @property source - * @type Image - */ - this.source = source; - - if(!source)return; - - if(this.source instanceof Image || this.source instanceof HTMLImageElement) - { - if(this.source.complete) - { - this.hasLoaded = true; - this.width = this.source.width; - this.height = this.source.height; - - PIXI.texturesToUpdate.push(this); - } - else - { - - var scope = this; - this.source.onload = function(){ - - scope.hasLoaded = true; - scope.width = scope.source.width; - scope.height = scope.source.height; - - // add it to somewhere... - PIXI.texturesToUpdate.push(scope); - scope.dispatchEvent( { type: 'loaded', content: scope } ); - } - // this.image.src = imageUrl; - } - } - else - { - this.hasLoaded = true; - this.width = this.source.width; - this.height = this.source.height; - - PIXI.texturesToUpdate.push(this); - } - - this._powerOf2 = false; -} - -PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture; - -/** - * Destroys this base texture - * - * @method destroy - */ -PIXI.BaseTexture.prototype.destroy = function() -{ - if(this.source instanceof Image) - { - this.source.src = null; - } - this.source = null; - PIXI.texturesToDestroy.push(this); -} - -/** - * Helper function that returns a base texture based on an image url - * If the image is not in the base texture cache it will be created and loaded - * - * @static - * @method fromImage - * @param imageUrl {String} The image url of the texture - * @return BaseTexture - */ -PIXI.BaseTexture.fromImage = function(imageUrl, crossorigin) -{ - var baseTexture = PIXI.BaseTextureCache[imageUrl]; - if(!baseTexture) - { - // new Image() breaks tex loading in some versions of Chrome. - // See https://code.google.com/p/chromium/issues/detail?id=238071 - var image = new Image();//document.createElement('img'); - if (crossorigin) - { - image.crossOrigin = ''; - } - image.src = imageUrl; - baseTexture = new PIXI.BaseTexture(image); - PIXI.BaseTextureCache[imageUrl] = baseTexture; - } - - return baseTexture; -} - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -PIXI.TextureCache = {}; -PIXI.FrameCache = {}; - -/** - * A texture stores the information that represents an image or part of an image. It cannot be added - * to the display list directly. To do this use PIXI.Sprite. If no frame is provided then the whole image is used - * - * @class Texture - * @uses EventTarget - * @constructor - * @param baseTexture {BaseTexture} The base texture source to create the texture from - * @param frame {Rectangle} The rectangle frame of the texture to show - */ -PIXI.Texture = function(baseTexture, frame) -{ - PIXI.EventTarget.call( this ); - - if(!frame) - { - this.noFrame = true; - frame = new PIXI.Rectangle(0,0,1,1); - } - - if(baseTexture instanceof PIXI.Texture) - baseTexture = baseTexture.baseTexture; - - /** - * The base texture of this texture - * - * @property baseTexture - * @type BaseTexture - */ - this.baseTexture = baseTexture; - - /** - * The frame specifies the region of the base texture that this texture uses - * - * @property frame - * @type Rectangle - */ - this.frame = frame; - - /** - * The trim point - * - * @property trim - * @type Point - */ - this.trim = new PIXI.Point(); - - this.scope = this; - - if(baseTexture.hasLoaded) - { - if(this.noFrame)frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height); - //console.log(frame) - - this.setFrame(frame); - } - else - { - var scope = this; - baseTexture.addEventListener( 'loaded', function(){ scope.onBaseTextureLoaded()} ); - } -} - -PIXI.Texture.prototype.constructor = PIXI.Texture; - -/** - * Called when the base texture is loaded - * - * @method onBaseTextureLoaded - * @param event - * @private - */ -PIXI.Texture.prototype.onBaseTextureLoaded = function(event) -{ - var baseTexture = this.baseTexture; - baseTexture.removeEventListener( 'loaded', this.onLoaded ); - - if(this.noFrame)this.frame = new PIXI.Rectangle(0,0, baseTexture.width, baseTexture.height); - this.noFrame = false; - this.width = this.frame.width; - this.height = this.frame.height; - - this.scope.dispatchEvent( { type: 'update', content: this } ); -} - -/** - * Destroys this texture - * - * @method destroy - * @param destroyBase {Boolean} Whether to destroy the base texture as well - */ -PIXI.Texture.prototype.destroy = function(destroyBase) -{ - if(destroyBase)this.baseTexture.destroy(); -} - -/** - * Specifies the rectangle region of the baseTexture - * - * @method setFrame - * @param frame {Rectangle} The frame of the texture to set it to - */ -PIXI.Texture.prototype.setFrame = function(frame) -{ - this.frame = frame; - this.width = frame.width; - this.height = frame.height; - - if(frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height) - { - throw new Error("Texture Error: frame does not fit inside the base Texture dimensions " + this); - } - - this.updateFrame = true; - - PIXI.Texture.frameUpdates.push(this); - //this.dispatchEvent( { type: 'update', content: this } ); -} - -/** - * Helper function that returns a texture based on an image url - * If the image is not in the texture cache it will be created and loaded - * - * @static - * @method fromImage - * @param imageUrl {String} The image url of the texture - * @param crossorigin {Boolean} Whether requests should be treated as crossorigin - * @return Texture - */ -PIXI.Texture.fromImage = function(imageUrl, crossorigin) -{ - var texture = PIXI.TextureCache[imageUrl]; - - if(!texture) - { - texture = new PIXI.Texture(PIXI.BaseTexture.fromImage(imageUrl, crossorigin)); - PIXI.TextureCache[imageUrl] = texture; - } - - return texture; -} - -/** - * Helper function that returns a texture based on a frame id - * If the frame id is not in the texture cache an error will be thrown - * - * @static - * @method fromFrame - * @param frameId {String} The frame id of the texture - * @return Texture - */ -PIXI.Texture.fromFrame = function(frameId) -{ - var texture = PIXI.TextureCache[frameId]; - if(!texture)throw new Error("The frameId '"+ frameId +"' does not exist in the texture cache " + this); - return texture; -} - -/** - * Helper function that returns a texture based on a canvas element - * If the canvas is not in the texture cache it will be created and loaded - * - * @static - * @method fromCanvas - * @param canvas {Canvas} The canvas element source of the texture - * @return Texture - */ -PIXI.Texture.fromCanvas = function(canvas) -{ - var baseTexture = new PIXI.BaseTexture(canvas); - return new PIXI.Texture(baseTexture); -} - - -/** - * Adds a texture to the textureCache. - * - * @static - * @method addTextureToCache - * @param texture {Texture} - * @param id {String} the id that the texture will be stored against. - */ -PIXI.Texture.addTextureToCache = function(texture, id) -{ - PIXI.TextureCache[id] = texture; -} - -/** - * Remove a texture from the textureCache. - * - * @static - * @method removeTextureFromCache - * @param id {String} the id of the texture to be removed - * @return {Texture} the texture that was removed - */ -PIXI.Texture.removeTextureFromCache = function(id) -{ - var texture = PIXI.TextureCache[id] - PIXI.TextureCache[id] = null; - return texture; -} - -// this is more for webGL.. it contains updated frames.. -PIXI.Texture.frameUpdates = []; - - -/** - * @author Mat Groves http://matgroves.com/ @Doormat23 - */ - -/** - A RenderTexture is a special texture that allows any pixi displayObject to be rendered to it. - - __Hint__: All DisplayObjects (exmpl. Sprites) that renders on RenderTexture should be preloaded. - Otherwise black rectangles will be drawn instead. - - RenderTexture takes snapshot of DisplayObject passed to render method. If DisplayObject is passed to render method, position and rotation of it will be ignored. For example: - - var renderTexture = new PIXI.RenderTexture(800, 600); - var sprite = PIXI.Sprite.fromImage("spinObj_01.png"); - sprite.position.x = 800/2; - sprite.position.y = 600/2; - sprite.anchor.x = 0.5; - sprite.anchor.y = 0.5; - renderTexture.render(sprite); - - Sprite in this case will be rendered to 0,0 position. To render this sprite at center DisplayObjectContainer should be used: - - var doc = new PIXI.DisplayObjectContainer(); - doc.addChild(sprite); - renderTexture.render(doc); // Renders to center of renderTexture - - @class RenderTexture - @extends Texture - @constructor - @param width {Number} The width of the render texture - @param height {Number} The height of the render texture - */ -PIXI.RenderTexture = function(width, height) -{ - PIXI.EventTarget.call( this ); - - this.width = width || 100; - this.height = height || 100; - - this.indetityMatrix = PIXI.mat3.create(); - - this.frame = new PIXI.Rectangle(0, 0, this.width, this.height); - - if(PIXI.gl) - { - this.initWebGL(); - } - else - { - this.initCanvas(); - } -} - -PIXI.RenderTexture.prototype = Object.create( PIXI.Texture.prototype ); -PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture; - -/** - * Initializes the webgl data for this texture - * - * @method initWebGL - * @private - */ -PIXI.RenderTexture.prototype.initWebGL = function() -{ - var gl = PIXI.gl; - this.glFramebuffer = gl.createFramebuffer(); - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer ); - - this.glFramebuffer.width = this.width; - this.glFramebuffer.height = this.height; - - this.baseTexture = new PIXI.BaseTexture(); - - this.baseTexture.width = this.width; - this.baseTexture.height = this.height; - - this.baseTexture._glTexture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture); - - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - - this.baseTexture.isRender = true; - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer ); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.baseTexture._glTexture, 0); - - // create a projection matrix.. - this.projection = new PIXI.Point(this.width/2 , -this.height/2); - - // set the correct render function.. - this.render = this.renderWebGL; -} - - -PIXI.RenderTexture.prototype.resize = function(width, height) -{ - - this.width = width; - this.height = height; - - if(PIXI.gl) - { - this.projection.x = this.width/2 - this.projection.y = -this.height/2; - - var gl = PIXI.gl; - gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - } - else - { - - this.frame.width = this.width - this.frame.height = this.height; - this.renderer.resize(this.width, this.height); - } -} - -/** - * Initializes the canvas data for this texture - * - * @method initCanvas - * @private - */ -PIXI.RenderTexture.prototype.initCanvas = function() -{ - this.renderer = new PIXI.CanvasRenderer(this.width, this.height, null, 0); - - this.baseTexture = new PIXI.BaseTexture(this.renderer.view); - this.frame = new PIXI.Rectangle(0, 0, this.width, this.height); - - this.render = this.renderCanvas; -} - -/** - * This function will draw the display object to the texture. - * - * @method renderWebGL - * @param displayObject {DisplayObject} The display object to render this texture on - * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn - * @private - */ -PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, position, clear) -{ - var gl = PIXI.gl; - - // enable the alpha color mask.. - gl.colorMask(true, true, true, true); - - gl.viewport(0, 0, this.width, this.height); - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer ); - - if(clear) - { - gl.clearColor(0,0,0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - - // THIS WILL MESS WITH HIT TESTING! - var children = displayObject.children; - - //TODO -? create a new one??? dont think so! - var originalWorldTransform = displayObject.worldTransform; - displayObject.worldTransform = PIXI.mat3.create();//sthis.indetityMatrix; - // modify to flip... - displayObject.worldTransform[4] = -1; - displayObject.worldTransform[5] = this.projection.y * -2; - - if(position) - { - displayObject.worldTransform[2] = position.x; - displayObject.worldTransform[5] -= position.y; - } - - PIXI.visibleCount++; - displayObject.vcount = PIXI.visibleCount; - - for(var i=0,j=children.length; i>1; - if(n<3) return []; - var tgs = []; - var avl = []; - for(var i=0; i 3) - { - var i0 = avl[(i+0)%al]; - var i1 = avl[(i+1)%al]; - var i2 = avl[(i+2)%al]; - - var ax = p[2*i0], ay = p[2*i0+1]; - var bx = p[2*i1], by = p[2*i1+1]; - var cx = p[2*i2], cy = p[2*i2+1]; - - var earFound = false; - if(PIXI.PolyK._convex(ax, ay, bx, by, cx, cy, sign)) - { - earFound = true; - for(var j=0; j 3*al) - { - // need to flip flip reverse it! - // reset! - if(sign) - { - var tgs = []; - avl = []; - for(var i=0; i= 0) && (v >= 0) && (u + v < 1); -} - -/** - * Checks if a shape is convex - * - * @class _convex - * @namespace PolyK - * @private - */ -PIXI.PolyK._convex = function(ax, ay, bx, by, cx, cy, sign) -{ - return ((ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0) == sign; -} - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view. -* The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y -* -* @class Phaser.Camera -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. -* @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera -* @param {number} x - Position of the camera on the X axis -* @param {number} y - Position of the camera on the Y axis -* @param {number} width - The width of the view rectangle -* @param {number} height - The height of the view rectangle -*/ -Phaser.Camera = function (game, id, x, y, width, height) { - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {Phaser.World} world - A reference to the game world. - */ - this.world = game.world; - - /** - * @property {number} id - Reserved for future multiple camera set-ups. - * @default - */ - this.id = 0; - - /** - * Camera view. - * The view into the world we wish to render (by default the game dimensions). - * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render. - * Objects outside of this view are not rendered (unless set to ignore the Camera, i.e. UI?). - * @property {Phaser.Rectangle} view - */ - this.view = new Phaser.Rectangle(x, y, width, height); - - /** - * @property {Phaser.Rectangle} screenView - Used by Sprites to work out Camera culling. - */ - this.screenView = new Phaser.Rectangle(x, y, width, height); - - /** - * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World. - * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound - * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the center of the world. - * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere. - */ - this.bounds = new Phaser.Rectangle(x, y, width, height); - - /** - * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause camera moving. - */ - this.deadzone = null; - - /** - * @property {boolean} visible - Whether this camera is visible or not. - * @default - */ - this.visible = true; - - /** - * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not. - */ - this.atLimit = { x: false, y: false }; - - /** - * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null. - * @default - */ - this.target = null; - - /** - * @property {number} edge - Edge property. - * @private - * @default - */ - this._edge = 0; - - this.displayObject = null; - -}; - -/** -* @constant -* @type {number} -*/ -Phaser.Camera.FOLLOW_LOCKON = 0; - -/** -* @constant -* @type {number} -*/ -Phaser.Camera.FOLLOW_PLATFORMER = 1; - -/** -* @constant -* @type {number} -*/ -Phaser.Camera.FOLLOW_TOPDOWN = 2; - -/** -* @constant -* @type {number} -*/ -Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3; - -Phaser.Camera.prototype = { - - /** - * Tells this camera which sprite to follow. - * @method Phaser.Camera#follow - * @param {Phaser.Sprite} target - The object you want the camera to track. Set to null to not follow anything. - * @param {number} [style] Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow(). - */ - follow: function (target, style) { - - if (typeof style === "undefined") { style = Phaser.Camera.FOLLOW_LOCKON; } - - this.target = target; - - var helper; - - switch (style) { - - case Phaser.Camera.FOLLOW_PLATFORMER: - var w = this.width / 8; - var h = this.height / 3; - this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h); - break; - - case Phaser.Camera.FOLLOW_TOPDOWN: - helper = Math.max(this.width, this.height) / 4; - this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); - break; - - case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT: - helper = Math.max(this.width, this.height) / 8; - this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper); - break; - - case Phaser.Camera.FOLLOW_LOCKON: - default: - this.deadzone = null; - break; - } - - }, - - /** - * Move the camera focus on a display object instantly. - * @method Phaser.Camera#focusOn - * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties. - */ - focusOn: function (displayObject) { - - this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight)); - - }, - - /** - * Move the camera focus on a location instantly. - * @method Phaser.Camera#focusOnXY - * @param {number} x - X position. - * @param {number} y - Y position. - */ - focusOnXY: function (x, y) { - - this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight)); - - }, - - /** - * Update focusing and scrolling. - * @method Phaser.Camera#update - */ - update: function () { - - if (this.target) - { - this.updateTarget(); - } - - if (this.bounds) - { - this.checkBounds(); - } - - this.displayObject.position.x = -this.view.x; - this.displayObject.position.y = -this.view.y; - - }, - - updateTarget: function () { - - if (this.deadzone) - { - this._edge = this.target.x - this.deadzone.x; - - if (this.view.x > this._edge) - { - this.view.x = this._edge; - } - - this._edge = this.target.x + this.target.width - this.deadzone.x - this.deadzone.width; - - if (this.view.x < this._edge) - { - this.view.x = this._edge; - } - - this._edge = this.target.y - this.deadzone.y; - - if (this.view.y > this._edge) - { - this.view.y = this._edge; - } - - this._edge = this.target.y + this.target.height - this.deadzone.y - this.deadzone.height; - - if (this.view.y < this._edge) - { - this.view.y = this._edge; - } - } - else - { - this.focusOnXY(this.target.x, this.target.y); - } - - }, - - setBoundsToWorld: function () { - - this.bounds.setTo(this.game.world.x, this.game.world.y, this.game.world.width, this.game.world.height); - - }, - - /** - * Method called to ensure the camera doesn't venture outside of the game world. - * @method Phaser.Camera#checkWorldBounds - */ - checkBounds: function () { - - this.atLimit.x = false; - this.atLimit.y = false; - - // Make sure we didn't go outside the cameras bounds - if (this.view.x < this.bounds.x) - { - this.atLimit.x = true; - this.view.x = this.bounds.x; - } - - if (this.view.x > this.bounds.right - this.width) - { - this.atLimit.x = true; - this.view.x = (this.bounds.right - this.width) + 1; - } - - if (this.view.y < this.bounds.top) - { - this.atLimit.y = true; - this.view.y = this.bounds.top; - } - - if (this.view.y > this.bounds.bottom - this.height) - { - this.atLimit.y = true; - this.view.y = (this.bounds.bottom - this.height) + 1; - } - - this.view.floor(); - - }, - - /** - * A helper function to set both the X and Y properties of the camera at once - * without having to use game.camera.x and game.camera.y. - * - * @method Phaser.Camera#setPosition - * @param {number} x - X position. - * @param {number} y - Y position. - */ - setPosition: function (x, y) { - - this.view.x = x; - this.view.y = y; - - if (this.bounds) - { - this.checkBounds(); - } - - }, - - /** - * Sets the size of the view rectangle given the width and height in parameters. - * - * @method Phaser.Camera#setSize - * @param {number} width - The desired width. - * @param {number} height - The desired height. - */ - setSize: function (width, height) { - - this.view.width = width; - this.view.height = height; - - } - -}; - -/** -* The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds. -* @name Phaser.Camera#x -* @property {number} x - Gets or sets the cameras x position. -*/ -Object.defineProperty(Phaser.Camera.prototype, "x", { - - get: function () { - return this.view.x; - }, - - set: function (value) { - - this.view.x = value; - - if (this.bounds) - { - this.checkBounds(); - } - } - -}); - -/** -* The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds. -* @name Phaser.Camera#y -* @property {number} y - Gets or sets the cameras y position. -*/ -Object.defineProperty(Phaser.Camera.prototype, "y", { - - get: function () { - return this.view.y; - }, - - set: function (value) { - - this.view.y = value; - - if (this.bounds) - { - this.checkBounds(); - } - } - -}); - -/** -* The Cameras width. By default this is the same as the Game size and should not be adjusted for now. -* @name Phaser.Camera#width -* @property {number} width - Gets or sets the cameras width. -*/ -Object.defineProperty(Phaser.Camera.prototype, "width", { - - get: function () { - return this.view.width; - }, - - set: function (value) { - this.view.width = value; - } - -}); - -/** -* The Cameras height. By default this is the same as the Game size and should not be adjusted for now. -* @name Phaser.Camera#height -* @property {number} height - Gets or sets the cameras height. -*/ -Object.defineProperty(Phaser.Camera.prototype, "height", { - - get: function () { - return this.view.height; - }, - - set: function (value) { - this.view.height = value; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* This is a base State class which can be extended if you are creating your own game. -* It provides quick access to common functions such as the camera, cache, input, match, sound and more. -* -* @class Phaser.State -* @constructor -*/ - -Phaser.State = function () { - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = null; - - /** - * @property {Phaser.GameObjectFactory} add - Reference to the GameObjectFactory. - * @default - */ - this.add = null; - - /** - * @property {Phaser.Physics.PhysicsManager} camera - A handy reference to world.camera. - * @default - */ - this.camera = null; - - /** - * @property {Phaser.Cache} cache - Reference to the assets cache. - * @default - */ - this.cache = null; - - /** - * @property {Phaser.Input} input - Reference to the input manager - * @default - */ - this.input = null; - - /** - * @property {Phaser.Loader} load - Reference to the assets loader. - * @default - */ - this.load = null; - - /** - * @property {Phaser.Math} math - Reference to the math helper. - * @default - */ - this.math = null; - - /** - * @property {Phaser.SoundManager} sound - Reference to the sound manager. - * @default - */ - this.sound = null; - - /** - * @property {Phaser.Stage} stage - Reference to the stage. - * @default - */ - this.stage = null; - - /** - * @property {Phaser.TimeManager} time - Reference to game clock. - * @default - */ - this.time = null; - - /** - * @property {Phaser.TweenManager} tweens - Reference to the tween manager. - * @default - */ - this.tweens = null; - - /** - * @property {Phaser.World} world - Reference to the world. - * @default - */ - this.world = null; - - /** - * @property {Description} add - Description. - * @default - */ - this.particles = null; - - /** - * @property {Phaser.Physics.PhysicsManager} physics - Reference to the physics manager. - * @default - */ - this.physics = null; - -}; - -Phaser.State.prototype = { - - /** - * Override this method to add some load operations. - * If you need to use the loader, you may need to use them here. - * - * @method Phaser.State#preload - */ - preload: function () { - }, - - /** - * Put update logic here. - * - * @method Phaser.State#loadUpdate - */ - loadUpdate: function () { - }, - - /** - * Put render operations here. - * - * @method Phaser.State#loadRender - */ - loadRender: function () { - }, - - /** - * This method is called after the game engine successfully switches states. - * Feel free to add any setup code here (do not load anything here, override preload() instead). - * - * @method Phaser.State#create - */ - create: function () { - }, - - /** - * Put update logic here. - * - * @method Phaser.State#update - */ - update: function () { - }, - - /** - * Put render operations here. - * - * @method Phaser.State#render - */ - render: function () { - }, - - /** - * This method will be called when game paused. - * - * @method Phaser.State#paused - */ - paused: function () { - }, - - /** - * This method will be called when the state is destroyed. - * @method Phaser.State#destroy - */ - destroy: function () { - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The State Manager is responsible for loading, setting up and switching game states. -* -* @class Phaser.StateManager -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with. -*/ -Phaser.StateManager = function (game, pendingState) { - - /** - * A reference to the currently running game. - * @property {Phaser.Game} game. - */ - this.game = game; - - /** - * Description. - * @property {Description} states. - */ - this.states = {}; - - if (pendingState !== null) - { - this._pendingState = pendingState; - } - -}; - -Phaser.StateManager.prototype = { - - /** - * A reference to the currently running game. - * @property {Phaser.Game} game. - */ - game: null, - - /** - * The state to be switched to in the next frame. - * @property {State} _pendingState - * @private - */ - _pendingState: null, - - /** - * Flag that sets if the State has been created or not. - * @property {boolean}_created - * @private - */ - _created: false, - - /** - * The state to be switched to in the next frame. - * @property {Description} states - */ - states: {}, - - /** - * The current active State object (defaults to null). - * @property {string} current - */ - current: '', - - /** - * This will be called when the state is started (i.e. set as the current active state). - * @property {function} onInitCallback - */ - onInitCallback: null, - - /** - * This will be called when init states (loading assets...). - * @property {function} onPreloadCallback - */ - onPreloadCallback: null, - - /** - * This will be called when create states (setup states...). - * @property {function} onCreateCallback - */ - onCreateCallback: null, - - /** - * This will be called when State is updated, this doesn't happen during load (@see onLoadUpdateCallback). - * @property {function} onUpdateCallback - */ - onUpdateCallback: null, - - /** - * This will be called when the State is rendered, this doesn't happen during load (see onLoadRenderCallback). - * @property {function} onRenderCallback - */ - onRenderCallback: null, - - /** - * This will be called before the State is rendered and before the stage is cleared. - * @property {function} onPreRenderCallback - */ - onPreRenderCallback: null, - - /** - * This will be called when the State is updated but only during the load process. - * @property {function} onLoadUpdateCallback - */ - onLoadUpdateCallback: null, - - /** - * This will be called when the State is rendered but only during the load process. - * @property {function} onLoadRenderCallback - */ - onLoadRenderCallback: null, - - /** - * This will be called when states paused. - * @property {function} onPausedCallback - */ - onPausedCallback: null, - - /** - * This will be called when the state is shut down (i.e. swapped to another state). - * @property {function} onShutDownCallback - */ - onShutDownCallback: null, - - /** - * Description. - * @method Phaser.StateManager#boot - * @private - */ - boot: function () { - - // console.log('Phaser.StateManager.boot'); - - if (this._pendingState !== null) - { - // console.log('_pendingState found'); - // console.log(typeof this._pendingState); - - if (typeof this._pendingState === 'string') - { - // State was already added, so just start it - this.start(this._pendingState, false, false); - } - else - { - this.add('default', this._pendingState, true); - } - - } - - }, - - /** - * Add a new State. - * @method Phaser.StateManager#add - * @param key {string} - A unique key you use to reference this state, i.e. "MainMenu", "Level1". - * @param state {State} - The state you want to switch to. - * @param autoStart {boolean} - Start the state immediately after creating it? (default true) - */ - add: function (key, state, autoStart) { - - if (typeof autoStart === "undefined") { autoStart = false; } - - // console.log('Phaser.StateManager.addState', key); - // console.log(typeof state); - // console.log('autoStart?', autoStart); - - var newState; - - if (state instanceof Phaser.State) - { - // console.log('Phaser.StateManager.addState: Phaser.State given'); - newState = state; - } - else if (typeof state === 'object') - { - // console.log('Phaser.StateManager.addState: Object given'); - newState = state; - newState.game = this.game; - } - else if (typeof state === 'function') - { - // console.log('Phaser.StateManager.addState: Function given'); - newState = new state(this.game); - } - - this.states[key] = newState; - - if (autoStart) - { - if (this.game.isBooted) - { - // console.log('Game is booted, so we can start the state now'); - this.start(key); - } - else - { - // console.log('Game is NOT booted, so set the current state as pending'); - this._pendingState = key; - } - } - - return newState; - - }, - - /** - * Delete the given state. - * @method Phaser.StateManager#remove - * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1". - */ - remove: function (key) { - - if (this.current == key) - { - this.callbackContext = null; - - this.onInitCallback = null; - this.onShutDownCallback = null; - - this.onPreloadCallback = null; - this.onLoadRenderCallback = null; - this.onLoadUpdateCallback = null; - this.onCreateCallback = null; - this.onUpdateCallback = null; - this.onRenderCallback = null; - this.onPausedCallback = null; - this.onDestroyCallback = null; - } - - delete this.states[key]; - - }, - - /** - * Start the given state - * @method Phaser.StateManager#start - * @param {string} key - The key of the state you want to start. - * @param {boolean} [clearWorld] - clear everything in the world? (Default to true) - * @param {boolean} [clearCache] - clear asset cache? (Default to false and ONLY available when clearWorld=true) - */ - start: function (key, clearWorld, clearCache) { - - // console.log('Phaser.StateManager.start', key); - // console.log(this); - // console.log(this.callbackContext); - - if (typeof clearWorld === "undefined") { clearWorld = true; } - if (typeof clearCache === "undefined") { clearCache = false; } - - if (this.game.isBooted == false) - { - // console.log('Game is NOT booted, so set the requested state as pending'); - this._pendingState = key; - return; - } - - if (this.checkState(key) == false) - { - return; - } - else - { - // Already got a state running? - if (this.current) - { - this.onShutDownCallback.call(this.callbackContext, this.game); - } - - if (clearWorld) - { - this.game.tweens.removeAll(); - - this.game.world.destroy(); - - if (clearCache == true) - { - this.game.cache.destroy(); - } - } - - this.setCurrentState(key); - } - - if (this.onPreloadCallback) - { - // console.log('Preload Callback found'); - this.game.load.reset(); - this.onPreloadCallback.call(this.callbackContext, this.game); - - // Is the loader empty? - if (this.game.load.queueSize == 0) - { - // console.log('Loader queue empty'); - this.game.loadComplete(); - } - else - { - // console.log('Loader started'); - // Start the loader going as we have something in the queue - this.game.load.start(); - } - } - else - { - // console.log('Preload callback not found'); - // No init? Then there was nothing to load either - this.game.loadComplete(); - } - - }, - - /** - * Used by onInit and onShutdown when those functions don't exist on the state - * @method Phaser.StateManager#dummy - * @private - */ - dummy: function () { - }, - - /** - * Description. - * @method Phaser.StateManager#checkState - * @param {string} key - The key of the state you want to check. - * @return {boolean} Description. - */ - checkState: function (key) { - - if (this.states[key]) - { - var valid = false; - - if (this.states[key]['preload']) { valid = true; } - - if (valid == false && this.states[key]['loadRender']) { valid = true; } - if (valid == false && this.states[key]['loadUpdate']) { valid = true; } - if (valid == false && this.states[key]['create']) { valid = true; } - if (valid == false && this.states[key]['update']) { valid = true; } - if (valid == false && this.states[key]['preRender']) { valid = true; } - if (valid == false && this.states[key]['render']) { valid = true; } - if (valid == false && this.states[key]['paused']) { valid = true; } - - if (valid == false) - { - console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions."); - return false; - } - - return true; - } - else - { - console.warn("Phaser.StateManager - No state found with the key: " + key); - return false; - } - - }, - - /** - * Links game properties to the State given by the key. - * @method Phaser.StateManager#link - * @param {string} key - State key. - * @protected - */ - link: function (key) { - - // console.log('linked'); - this.states[key].game = this.game; - this.states[key].add = this.game.add; - this.states[key].camera = this.game.camera; - this.states[key].cache = this.game.cache; - this.states[key].input = this.game.input; - this.states[key].load = this.game.load; - this.states[key].math = this.game.math; - this.states[key].sound = this.game.sound; - this.states[key].stage = this.game.stage; - this.states[key].time = this.game.time; - this.states[key].tweens = this.game.tweens; - this.states[key].world = this.game.world; - this.states[key].particles = this.game.particles; - this.states[key].physics = this.game.physics; - this.states[key].rnd = this.game.rnd; - - }, - - /** - * Sets the current State. Should not be called directly (use StateManager.start) - * @method Phaser.StateManager#setCurrentState - * @param {string} key - State key. - * @protected - */ - setCurrentState: function (key) { - - this.callbackContext = this.states[key]; - - this.link(key); - - // Used when the state is set as being the current active state - this.onInitCallback = this.states[key]['init'] || this.dummy; - - this.onPreloadCallback = this.states[key]['preload'] || null; - this.onLoadRenderCallback = this.states[key]['loadRender'] || null; - this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null; - this.onCreateCallback = this.states[key]['create'] || null; - this.onUpdateCallback = this.states[key]['update'] || null; - this.onPreRenderCallback = this.states[key]['preRender'] || null; - this.onRenderCallback = this.states[key]['render'] || null; - this.onPausedCallback = this.states[key]['paused'] || null; - - // Used when the state is no longer the current active state - this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy; - - this.current = key; - this._created = false; - - this.onInitCallback.call(this.callbackContext, this.game); - - }, - - /** - * @method Phaser.StateManager#loadComplete - * @protected - */ - loadComplete: function () { - - // console.log('Phaser.StateManager.loadComplete'); - - if (this._created == false && this.onCreateCallback) - { - // console.log('Create callback found'); - this._created = true; - this.onCreateCallback.call(this.callbackContext, this.game); - } - else - { - this._created = true; - } - - }, - - /** - * @method Phaser.StateManager#update - * @protected - */ - update: function () { - - if (this._created && this.onUpdateCallback) - { - this.onUpdateCallback.call(this.callbackContext, this.game); - } - else - { - if (this.onLoadUpdateCallback) - { - this.onLoadUpdateCallback.call(this.callbackContext, this.game); - } - } - - }, - - /** - * @method Phaser.StateManager#preRender - * @protected - */ - preRender: function () { - - if (this.onPreRenderCallback) - { - this.onPreRenderCallback.call(this.callbackContext, this.game); - } - - }, - - /** - * @method Phaser.StateManager#render - * @protected - */ - render: function () { - - if (this._created && this.onRenderCallback) - { - if (this.game.renderType === Phaser.CANVAS) - { - this.game.context.save(); - this.game.context.setTransform(1, 0, 0, 1, 0, 0); - } - - this.onRenderCallback.call(this.callbackContext, this.game); - - if (this.game.renderType === Phaser.CANVAS) - { - this.game.context.restore(); - } - } - else - { - if (this.onLoadRenderCallback) - { - this.onLoadRenderCallback.call(this.callbackContext, this.game); - } - } - - }, - - /** - * Nuke the entire game from orbit - * @method Phaser.StateManager#destroy - */ - destroy: function () { - - this.callbackContext = null; - - this.onInitCallback = null; - this.onShutDownCallback = null; - - this.onPreloadCallback = null; - this.onLoadRenderCallback = null; - this.onLoadUpdateCallback = null; - this.onCreateCallback = null; - this.onUpdateCallback = null; - this.onRenderCallback = null; - this.onPausedCallback = null; - this.onDestroyCallback = null; - - this.game = null; - this.states = {}; - this._pendingState = null; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A basic linked list data structure. -* -* @class Phaser.LinkedList -* @constructor -*/ -Phaser.LinkedList = function () { - - /** - * @property {object} next - Next element in the list. - * @default - */ - this.next = null; - - /** - * @property {object} prev - Previous element in the list. - * @default - */ - this.prev = null; - - /** - * @property {object} first - First element in the list. - * @default - */ - this.first = null; - - /** - * @property {object} last - Last element in the list. - * @default - */ - this.last = null; - - /** - * @property {object} game - Number of elements in the list. - * @default - */ - this.total = 0; - -}; - -Phaser.LinkedList.prototype = { - - /** - * Adds a new element to this linked list. - * - * @method Phaser.LinkedList#add - * @param {object} child - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through. - * @return {object} The child that was added. - */ - add: function (child) { - - // If the list is empty - if (this.total == 0 && this.first == null && this.last == null) - { - this.first = child; - this.last = child; - this.next = child; - child.prev = this; - this.total++; - return child; - } - - // Get gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list) - this.last.next = child; - - child.prev = this.last; - - this.last = child; - - this.total++; - - return child; - - }, - - /** - * Removes the given element from this linked list if it exists. - * - * @method Phaser.LinkedList#remove - * @param {object} child - The child to be removed from the list. - */ - remove: function (child) { - - if (child == this.first) - { - // It was 'first', make 'first' point to first.next - this.first = this.first.next; - } - else if (child == this.last) - { - // It was 'last', make 'last' point to last.prev - this.last = this.last.prev; - } - - if (child.prev) - { - // make child.prev.next point to childs.next instead of child - child.prev.next = child.next; - } - - if (child.next) - { - // make child.next.prev point to child.prev instead of child - child.next.prev = child.prev; - } - - child.next = child.prev = null; - - if (this.first == null ) - { - this.last = null; - } - - this.total--; - - }, - - /** - * Calls a function on all members of this list, using the member as the context for the callback. - * The function must exist on the member. - * - * @method Phaser.LinkedList#callAll - * @param {function} callback - The function to call. - */ - callAll: function (callback) { - - if (!this.first || !this.last) - { - return; - } - - var entity = this.first; - - do - { - if (entity && entity[callback]) - { - entity[callback].call(entity); - } - - entity = entity.next; - - } - while(entity != this.last.next) - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* @class Phaser.Signal -* @classdesc A Signal is used for object communication via a custom broadcaster instead of Events. -* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ -* @constructor -*/ -Phaser.Signal = function () { - - /** - * @property {Array.} _bindings - Description. - * @private - */ - this._bindings = []; - - /** - * @property {Description} _prevParams - Description. - * @private - */ - this._prevParams = null; - - // enforce dispatch to aways work on same context (#47) - var self = this; - - /** - * @property {Description} dispatch - Description. - */ - this.dispatch = function(){ - Phaser.Signal.prototype.dispatch.apply(self, arguments); - }; - -}; - -Phaser.Signal.prototype = { - - /** - * If Signal should keep record of previously dispatched parameters and - * automatically execute listener during `add()`/`addOnce()` if Signal was - * already dispatched before. - * @property {boolean} memorize - */ - memorize: false, - - /** - * @property {boolean} _shouldPropagate - * @private - */ - _shouldPropagate: true, - - /** - * If Signal is active and should broadcast events. - *

IMPORTANT: Setting this property during a dispatch will only affect the next dispatch, if you want to stop the propagation of a signal use `halt()` instead.

- * @property {boolean} active - * @default - */ - active: true, - - /** - * @method Phaser.Signal#validateListener - * @param {function} listener - Signal handler function. - * @param {Description} fnName - Description. - * @private - */ - validateListener: function (listener, fnName) { - if (typeof listener !== 'function') { - throw new Error( 'listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName) ); - } - }, - - /** - * @method Phaser.Signal#_registerListener - * @param {function} listener - Signal handler function. - * @param {boolean} isOnce - Description. - * @param {object} [listenerContext] - Description. - * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - * @private - */ - _registerListener: function (listener, isOnce, listenerContext, priority) { - - var prevIndex = this._indexOfListener(listener, listenerContext), - binding; - - if (prevIndex !== -1) { - binding = this._bindings[prevIndex]; - if (binding.isOnce() !== isOnce) { - throw new Error('You cannot add'+ (isOnce? '' : 'Once') +'() then add'+ (!isOnce? '' : 'Once') +'() the same listener without removing the relationship first.'); - } - } else { - binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority); - this._addBinding(binding); - } - - if (this.memorize && this._prevParams){ - binding.execute(this._prevParams); - } - - return binding; - }, - - /** - * @method Phaser.Signal#_addBinding - * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener. - * @private - */ - _addBinding: function (binding) { - //simplified insertion sort - var n = this._bindings.length; - do { --n; } while (this._bindings[n] && binding._priority <= this._bindings[n]._priority); - this._bindings.splice(n + 1, 0, binding); - }, - - /** - * @method Phaser.Signal#_indexOfListener - * @param {function} listener - Signal handler function. - * @return {number} Description. - * @private - */ - _indexOfListener: function (listener, context) { - var n = this._bindings.length, - cur; - while (n--) { - cur = this._bindings[n]; - if (cur._listener === listener && cur.context === context) { - return n; - } - } - return -1; - }, - - /** - * Check if listener was attached to Signal. - * - * @method Phaser.Signal#has - * @param {Function} listener - Signal handler function. - * @param {Object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @return {boolean} If Signal has the specified listener. - */ - has: function (listener, context) { - return this._indexOfListener(listener, context) !== -1; - }, - - /** - * Add a listener to the signal. - * - * @method Phaser.Signal#add - * @param {function} listener - Signal handler function. - * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0). - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - */ - add: function (listener, listenerContext, priority) { - this.validateListener(listener, 'add'); - return this._registerListener(listener, false, listenerContext, priority); - }, - - /** - * Add listener to the signal that should be removed after first execution (will be executed only once). - * - * @method Phaser.Signal#addOnce - * @param {function} listener Signal handler function. - * @param {object} [listenerContext] Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @param {number} [priority] The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0) - * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener. - */ - addOnce: function (listener, listenerContext, priority) { - this.validateListener(listener, 'addOnce'); - return this._registerListener(listener, true, listenerContext, priority); - }, - - /** - * Remove a single listener from the dispatch queue. - * - * @method Phaser.Signal#remove - * @param {function} listener Handler function that should be removed. - * @param {object} [context] Execution context (since you can add the same handler multiple times if executing in a different context). - * @return {function} Listener handler function. - */ - remove: function (listener, context) { - - this.validateListener(listener, 'remove'); - - var i = this._indexOfListener(listener, context); - - if (i !== -1) - { - this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal - this._bindings.splice(i, 1); - } - - return listener; - - }, - - /** - * Remove all listeners from the Signal. - * - * @method Phaser.Signal#removeAll - */ - removeAll: function () { - var n = this._bindings.length; - while (n--) { - this._bindings[n]._destroy(); - } - this._bindings.length = 0; - }, - - /** - * Gets the total number of listeneres attached to ths Signal. - * - * @method Phaser.Signal#getNumListeners - * @return {number} Number of listeners attached to the Signal. - */ - getNumListeners: function () { - return this._bindings.length; - }, - - /** - * Stop propagation of the event, blocking the dispatch to next listeners on the queue. - *

IMPORTANT: should be called only during signal dispatch, calling it before/after dispatch won't affect signal broadcast.

- * @see Signal.prototype.disable - * - * @method Phaser.Signal#halt - */ - halt: function () { - this._shouldPropagate = false; - }, - - /** - * Dispatch/Broadcast Signal to all listeners added to the queue. - * - * @method Phaser.Signal#dispatch - * @param {any} [params] - Parameters that should be passed to each handler. - */ - dispatch: function (params) { - if (! this.active) { - return; - } - - var paramsArr = Array.prototype.slice.call(arguments), - n = this._bindings.length, - bindings; - - if (this.memorize) { - this._prevParams = paramsArr; - } - - if (! n) { - //should come after memorize - return; - } - - bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch - this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch. - - //execute all callbacks until end of the list or until a callback returns `false` or stops propagation - //reverse loop since listeners with higher priority will be added at the end of the list - do { n--; } while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false); - }, - - /** - * Forget memorized arguments. - * @see Signal.memorize - * - * @method Phaser.Signal#forget - */ - forget: function(){ - this._prevParams = null; - }, - - /** - * Remove all bindings from signal and destroy any reference to external objects (destroy Signal object). - *

IMPORTANT: calling any method on the signal instance after calling dispose will throw errors.

- * - * @method Phaser.Signal#dispose - */ - dispose: function () { - this.removeAll(); - delete this._bindings; - delete this._prevParams; - }, - - /** - * - * @method Phaser.Signal#toString - * @return {string} String representation of the object. - */ - toString: function () { - return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']'; - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser.SignalBinding -* -* Object that represents a binding between a Signal and a listener function. -*
- This is an internal constructor and shouldn't be called by regular users. -*
- inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes. -* -* @class Phaser.SignalBinding -* @name SignalBinding -* @author Miller Medeiros http://millermedeiros.github.com/js-signals/ -* @constructor -* @inner -* @param {Signal} signal - Reference to Signal object that listener is currently bound to. -* @param {function} listener - Handler function bound to the signal. -* @param {boolean} isOnce - If binding should be executed just once. -* @param {object} [listenerContext] - Context on which listener will be executed (object that should represent the `this` variable inside listener function). -* @param {number} [priority] - The priority level of the event listener. (default = 0). -*/ -Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority) { - - /** - * @property {Phaser.Game} _listener - Handler function bound to the signal. - * @private - */ - this._listener = listener; - - /** - * @property {boolean} _isOnce - If binding should be executed just once. - * @private - */ - this._isOnce = isOnce; - - /** - * @property {object|undefined|null} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function). - * @memberof SignalBinding.prototype - */ - this.context = listenerContext; - - /** - * @property {Signal} _signal - Reference to Signal object that listener is currently bound to. - * @private - */ - this._signal = signal; - - /** - * @property {number} _priority - Listener priority. - * @private - */ - this._priority = priority || 0; - -}; - -Phaser.SignalBinding.prototype = { - - /** - * If binding is active and should be executed. - * @property {boolean} active - * @default - */ - active: true, - - /** - * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters). - * @property {array|null} params - * @default - */ - params: null, - - /** - * Call listener passing arbitrary parameters. - *

If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.

- * @method Phaser.SignalBinding#execute - * @param {array} [paramsArr] - Array of parameters that should be passed to the listener. - * @return {Description} Value returned by the listener. - */ - execute: function (paramsArr) { - - var handlerReturn, params; - - if (this.active && !!this._listener) - { - params = this.params? this.params.concat(paramsArr) : paramsArr; - handlerReturn = this._listener.apply(this.context, params); - - if (this._isOnce) - { - this.detach(); - } - } - - return handlerReturn; - - }, - - /** - * Detach binding from signal. - *

alias to: @see mySignal.remove(myBinding.getListener()); - * @method Phaser.SignalBinding#detach - * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached. - */ - detach: function () { - return this.isBound() ? this._signal.remove(this._listener, this.context) : null; - }, - - /** - * @method Phaser.SignalBinding#isBound - * @return {boolean} True if binding is still bound to the signal and has a listener. - */ - isBound: function () { - return (!!this._signal && !!this._listener); - }, - - /** - * @method Phaser.SignalBinding#isOnce - * @return {boolean} If SignalBinding will only be executed once. - */ - isOnce: function () { - return this._isOnce; - }, - - /** - * @method Phaser.SignalBinding#getListener - * @return {Function} Handler function bound to the signal. - */ - getListener: function () { - return this._listener; - }, - - /** - * @method Phaser.SignalBinding#getSignal - * @return {Signal} Signal that listener is currently bound to. - */ - getSignal: function () { - return this._signal; - }, - - /** - * @method Phaser.SignalBinding#_destroy - * Delete instance properties - * @private - */ - _destroy: function () { - delete this._signal; - delete this._listener; - delete this.context; - }, - - /** - * @method Phaser.SignalBinding#toString - * @return {string} String representation of the object. - */ - toString: function () { - return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']'; - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* This is a base Filter template to use for any Phaser filter development. -* -* @class Phaser.Filter -* @classdesc Phaser - Filter -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Object} uniforms - Uniform mappings object -* @param {Array} fragmentSrc - The fragment shader code. -*/ -Phaser.Filter = function (game, uniforms, fragmentSrc) { - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER. - * @default - */ - this.type = Phaser.WEBGL_FILTER; - - /** - * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion. - * For example the blur filter has two passes blurX and blurY. - * @property {array} passes - An array of filter objects. - * @private - */ - this.passes = [this]; - - /** - * @property {boolean} dirty - Internal PIXI var. - * @default - */ - this.dirty = true; - - /** - * @property {number} padding - Internal PIXI var. - * @default - */ - this.padding = 0; - - /** - * @property {object} uniforms - Default uniform mappings. - */ - this.uniforms = { - - resolution: { type: '3f', value: { x: 256, y: 256, z: 0 }}, - time: { type: '1f', value: 0 }, - mouse: { type: '4f', value: { x: 0, y: 0, z: 0, w: 0 }} - - }; - - /** - * @property {array} fragmentSrc - The fragment shader code. - */ - this.fragmentSrc = fragmentSrc || []; - -}; - -Phaser.Filter.prototype = { - - init: function () { - // This should be over-ridden. Will receive a variable number of arguments. - }, - - setResolution: function (width, height) { - - this.uniforms.resolution.value.x = width; - this.uniforms.resolution.value.y = height; - - }, - - update: function (pointer) { - - if (typeof pointer !== 'undefined') - { - this.uniforms.mouse.x = pointer.x; - this.uniforms.mouse.y = pointer.y; - } - - this.uniforms.time.value = this.game.time.totalElapsedSeconds(); - - }, - - /** - * Clear down this Filter and null out references - * @method Phaser.Filter#destroy - */ - destroy: function () { - - this.game = null; - - } - -}; - -Object.defineProperty(Phaser.Filter.prototype, 'width', { - - get: function() { - return this.uniforms.resolution.value.x; - }, - - set: function(value) { - this.uniforms.resolution.value.x = value; - } - -}); - -Object.defineProperty(Phaser.Filter.prototype, 'height', { - - get: function() { - return this.uniforms.resolution.value.y; - }, - - set: function(value) { - this.uniforms.resolution.value.y = value; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* This is a base Plugin template to use for any Phaser plugin development. -* -* @class Phaser.Plugin -* @classdesc Phaser - Plugin -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Any} parent - The object that owns this plugin, usually Phaser.PluginManager. -*/ -Phaser.Plugin = function (game, parent) { - - if (typeof parent === 'undefined') { parent = null; } - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {Any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null. - */ - this.parent = parent; - - /** - * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped. - * @default - */ - this.active = false; - - /** - * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped. - * @default - */ - this.visible = false; - - /** - * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method. - * @default - */ - this.hasPreUpdate = false; - - /** - * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method. - * @default - */ - this.hasUpdate = false; - - /** - * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method. - * @default - */ - this.hasPostUpdate = false; - - /** - * @property {boolean} hasRender - A flag to indicate if this plugin has a render method. - * @default - */ - this.hasRender = false; - - /** - * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method. - * @default - */ - this.hasPostRender = false; - -}; - -Phaser.Plugin.prototype = { - - /** - * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). - * It is only called if active is set to true. - * @method Phaser.Plugin#preUpdate - */ - preUpdate: function () { - }, - - /** - * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. - * It is only called if active is set to true. - * @method Phaser.Plugin#update - */ - update: function () { - }, - - /** - * Render is called right after the Game Renderer completes, but before the State.render. - * It is only called if visible is set to true. - * @method Phaser.Plugin#render - */ - render: function () { - }, - - /** - * Post-render is called after the Game Renderer and State.render have run. - * It is only called if visible is set to true. - * @method Phaser.Plugin#postRender - */ - postRender: function () { - }, - - /** - * Clear down this Plugin and null out references - * @method Phaser.Plugin#destroy - */ - destroy: function () { - - this.game = null; - this.parent = null; - this.active = false; - this.visible = false; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Description. -* -* @class Phaser.PluginManager -* @classdesc Phaser - PluginManager -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Description} parent - Description. -*/ -Phaser.PluginManager = function(game, parent) { - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {Description} _parent - Description. - * @private - */ - this._parent = parent; - - /** - * @property {array} plugins - Description. - */ - this.plugins = []; - - /** - * @property {array} _pluginsLength - Description. - * @private - * @default - */ - this._pluginsLength = 0; - -}; - -Phaser.PluginManager.prototype = { - - /** - * Add a new Plugin to the PluginManager. - * The plugin's game and parent reference are set to this game and pluginmanager parent. - * @method Phaser.PluginManager#add - * @param {Phaser.Plugin} plugin - Description. - * @return {Phaser.Plugin} Description. - */ - add: function (plugin) { - - var result = false; - - // Prototype? - if (typeof plugin === 'function') - { - plugin = new plugin(this.game, this._parent); - } - else - { - plugin.game = this.game; - plugin.parent = this._parent; - } - - // Check for methods now to avoid having to do this every loop - if (typeof plugin['preUpdate'] === 'function') - { - plugin.hasPreUpdate = true; - result = true; - } - - if (typeof plugin['update'] === 'function') - { - plugin.hasUpdate = true; - result = true; - } - - if (typeof plugin['postUpdate'] === 'function') - { - plugin.hasPostUpdate = true; - result = true; - } - - if (typeof plugin['render'] === 'function') - { - plugin.hasRender = true; - result = true; - } - - if (typeof plugin['postRender'] === 'function') - { - plugin.hasPostRender = true; - result = true; - } - - // The plugin must have at least one of the above functions to be added to the PluginManager. - if (result) - { - if (plugin.hasPreUpdate || plugin.hasUpdate) - { - plugin.active = true; - } - - if (plugin.hasRender || plugin.hasPostRender) - { - plugin.visible = true; - } - - this._pluginsLength = this.plugins.push(plugin); - - // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager - if (typeof plugin['init'] === 'function') - { - plugin.init(); - } - - return plugin; - } - else - { - return null; - } - }, - - /** - * Remove a Plugin from the PluginManager. - * @method Phaser.PluginManager#remove - * @param {Phaser.Plugin} plugin - The plugin to be removed. - */ - remove: function (plugin) { - - if (this._pluginsLength == 0) - { - return; - } - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - if (this.plugins[this._p] === plugin) - { - plugin.destroy(); - this.plugins.splice(this._p, 1); - this._pluginsLength--; - return; - } - } - }, - - /** - * Removes all Plugins from the PluginManager. - * @method Phaser.PluginManager#removeAll - */ - removeAll: function() { - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - this.plugins[this._p].destroy(); - } - this.plugins.length = 0; - this._pluginsLength = 0; - }, - - /** - * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics). - * It only calls plugins who have active=true. - * - * @method Phaser.PluginManager#preUpdate - */ - preUpdate: function () { - - if (this._pluginsLength == 0) - { - return; - } - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - if (this.plugins[this._p].active && this.plugins[this._p].hasPreUpdate) - { - this.plugins[this._p].preUpdate(); - } - } - - }, - - /** - * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render. - * It only calls plugins who have active=true. - * - * @method Phaser.PluginManager#update - */ - update: function () { - - if (this._pluginsLength == 0) - { - return; - } - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - if (this.plugins[this._p].active && this.plugins[this._p].hasUpdate) - { - this.plugins[this._p].update(); - } - } - - }, - - /** - * PostUpdate is the last thing to be called before the world render. - * In particular, it is called after the world postUpdate, which means the camera has been adjusted. - * It only calls plugins who have active=true. - * - * @method Phaser.PluginManager#postUpdate - */ - postUpdate: function () { - - if (this._pluginsLength == 0) - { - return; - } - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - if (this.plugins[this._p].active && this.plugins[this._p].hasPostUpdate) - { - this.plugins[this._p].postUpdate(); - } - } - - }, - - /** - * Render is called right after the Game Renderer completes, but before the State.render. - * It only calls plugins who have visible=true. - * - * @method Phaser.PluginManager#render - */ - render: function () { - - if (this._pluginsLength == 0) - { - return; - } - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - if (this.plugins[this._p].visible && this.plugins[this._p].hasRender) - { - this.plugins[this._p].render(); - } - } - - }, - - /** - * Post-render is called after the Game Renderer and State.render have run. - * It only calls plugins who have visible=true. - * - * @method Phaser.PluginManager#postRender - */ - postRender: function () { - - if (this._pluginsLength == 0) - { - return; - } - - for (this._p = 0; this._p < this._pluginsLength; this._p++) - { - if (this.plugins[this._p].visible && this.plugins[this._p].hasPostRender) - { - this.plugins[this._p].postRender(); - } - } - - }, - - /** - * Clear down this PluginManager and null out references - * - * @method Phaser.PluginManager#destroy - */ - destroy: function () { - - this.plugins.length = 0; - this._pluginsLength = 0; - this.game = null; - this._parent = null; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Stage controls the canvas on which everything is displayed. It handles display within the browser, -* focus handling, game resizing, scaling and the pause, boot and orientation screens. -* -* @class Phaser.Stage -* @constructor -* @param {Phaser.Game} game - Game reference to the currently running game. -* @param {number} width - Width of the canvas element. -* @param {number} height - Height of the canvas element. - */ -Phaser.Stage = function (game, width, height) { - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {string} game - Background color of the stage (defaults to black). Set via the public backgroundColor property. - * @private - * @default 'rgb(0,0,0)' - */ - this._backgroundColor = 'rgb(0,0,0)'; - - /** - * @property {Phaser.Point} offset - Get the offset values (for input and other things). - */ - this.offset = new Phaser.Point; - - /** - * @property {HTMLCanvasElement} canvas - Reference to the newly created <canvas> element. - */ - this.canvas = Phaser.Canvas.create(width, height); - this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%'; - - /** - * @property {PIXI.Stage} _stage - The Pixi Stage which is hooked to the renderer. - * @private - */ - this._stage = new PIXI.Stage(0x000000, false); - this._stage.name = '_stage_root'; - this._stage.interactive = false; - - /** - * @property {number} scaleMode - The current scaleMode. - */ - this.scaleMode = Phaser.StageScaleMode.NO_SCALE; - - /** - * @property {Phaser.StageScaleMode} scale - The scale of the current running game. - */ - this.scale = new Phaser.StageScaleMode(this.game, width, height); - - /** - * @property {number} aspectRatio - Aspect ratio. - */ - this.aspectRatio = width / height; - - /** - * @property {number} _nextOffsetCheck - The time to run the next offset check. - * @private - */ - this._nextOffsetCheck = 0; - - /** - * @property {number|false} checkOffsetInterval - The time (in ms) between which the stage should check to see if it has moved. - * @default - */ - this.checkOffsetInterval = 2500; - -}; - -Phaser.Stage.prototype = { - - /** - * Initialises the stage and adds the event listeners. - * @method Phaser.Stage#boot - * @private - */ - boot: function () { - - Phaser.Canvas.getOffset(this.canvas, this.offset); - - this.bounds = new Phaser.Rectangle(this.offset.x, this.offset.y, this.game.width, this.game.height); - - var _this = this; - - this._onChange = function (event) { - return _this.visibilityChange(event); - } - - Phaser.Canvas.setUserSelect(this.canvas, 'none'); - Phaser.Canvas.setTouchAction(this.canvas, 'none'); - - document.addEventListener('visibilitychange', this._onChange, false); - document.addEventListener('webkitvisibilitychange', this._onChange, false); - document.addEventListener('pagehide', this._onChange, false); - document.addEventListener('pageshow', this._onChange, false); - - window.onblur = this._onChange; - window.onfocus = this._onChange; - - }, - - /** - * Runs Stage processes that need periodic updates, such as the offset checks. - * @method Phaser.Stage#update - */ - update: function () { - - if (this.checkOffsetInterval !== false) - { - if (this.game.time.now > this._nextOffsetCheck) - { - Phaser.Canvas.getOffset(this.canvas, this.offset); - this._nextOffsetCheck = this.game.time.now + this.checkOffsetInterval; - } - - } - - }, - - /** - * This method is called when the document visibility is changed. - * @method Phaser.Stage#visibilityChange - * @param {Event} event - Its type will be used to decide whether the game should be paused or not. - */ - visibilityChange: function (event) { - - if (this.disableVisibilityChange) - { - return; - } - - if (event.type == 'pagehide' || event.type == 'blur' || document['hidden'] == true || document['webkitHidden'] == true) - { - this.game.paused = true; - } - else - { - this.game.paused = false; - } - - }, - -}; - -/** -* @name Phaser.Stage#backgroundColor -* @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000' -*/ -Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", { - - get: function () { - return this._backgroundColor; - }, - - set: function (color) { - - this._backgroundColor = color; - - if (this.game.renderType == Phaser.CANVAS) - { - // Set it directly, this allows us to use rgb alpha values in Canvas mode. - this._stage.backgroundColorString = color; - } - else - { - if (typeof color === 'string') - { - color = Phaser.Color.hexToRGB(color); - } - - this._stage.setBackgroundColor(color); - } - - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser Group constructor. -* @class Phaser.Group -* @classdesc A Group is a container for display objects that allows for fast pooling, recycling and collision checks. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {*} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. -* @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. -* @param {boolean} [useStage=false] - Should the DisplayObjectContainer this Group creates be added to the World (default, false) or direct to the Stage (true). -*/ -Phaser.Group = function (game, parent, name, useStage) { - - if (typeof parent === 'undefined' || typeof parent === null) - { - parent = game.world; - } - - if (typeof useStage === 'undefined') - { - useStage = false; - } - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {string} name - A name for this Group. Not used internally but useful for debugging. - */ - this.name = name || 'group'; - - if (useStage) - { - this._container = this.game.stage._stage; - } - else - { - this._container = new PIXI.DisplayObjectContainer(); - this._container.name = this.name; - - if (parent) - { - if (parent instanceof Phaser.Group) - { - parent._container.addChild(this._container); - parent._container.updateTransform(); - } - else - { - parent.addChild(this._container); - parent.updateTransform(); - } - } - else - { - this.game.stage._stage.addChild(this._container); - this.game.stage._stage.updateTransform(); - } - } - - /** - * @property {number} type - Internal Phaser Type value. - * @protected - */ - this.type = Phaser.GROUP; - - /** - * @property {boolean} exists - If exists is true the the Group is updated, otherwise it is skipped. - * @default - */ - this.exists = true; - - /** - * @property {Phaser.Point} scale - Replaces the PIXI.Point with a slightly more flexible one. - */ - this.scale = new Phaser.Point(1, 1); - - /** - * The cursor is a simple way to iterate through the objects in a Group using the Group.next and Group.previous functions. - * The cursor is set to the first child added to the Group and doesn't change unless you call next, previous or set it directly with Group.cursor. - * @property {any} cursor - The current display object that the Group cursor is pointing to. - */ - this.cursor = null; - -}; - -/** -* @constant -* @type {number} -*/ -Phaser.Group.RETURN_NONE = 0; - -/** -* @constant -* @type {number} -*/ -Phaser.Group.RETURN_TOTAL = 1; - -/** -* @constant -* @type {number} -*/ -Phaser.Group.RETURN_CHILD = 2; - -/** -* @constant -* @type {number} -*/ -Phaser.Group.SORT_ASCENDING = -1; - -/** -* @constant -* @type {number} -*/ -Phaser.Group.SORT_DESCENDING = 1; - -Phaser.Group.prototype = { - - /** - * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object. - * The child is automatically added to the top of the Group, so renders on-top of everything else within the Group. If you need to control - * that then see the addAt method. - * - * @see Phaser.Group#create - * @see Phaser.Group#addAt - * @method Phaser.Group#add - * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object.. - * @return {*} The child that was added to the Group. - */ - add: function (child) { - - if (child.group !== this) - { - child.group = this; - - if (child.events) - { - child.events.onAddedToGroup.dispatch(child, this); - } - - this._container.addChild(child); - - child.updateTransform(); - - if (this.cursor === null) - { - this.cursor = child; - } - } - - return child; - - }, - - /** - * Adds an existing object to this Group. The object can be an instance of Phaser.Sprite, Phaser.Button or any other display object. - * The child is added to the Group at the location specified by the index value, this allows you to control child ordering. - * - * @method Phaser.Group#addAt - * @param {*} child - An instance of Phaser.Sprite, Phaser.Button or any other display object.. - * @param {number} index - The index within the Group to insert the child to. - * @return {*} The child that was added to the Group. - */ - addAt: function (child, index) { - - if (child.group !== this) - { - child.group = this; - - if (child.events) - { - child.events.onAddedToGroup.dispatch(child, this); - } - - this._container.addChildAt(child, index); - - child.updateTransform(); - - if (this.cursor === null) - { - this.cursor = child; - } - } - - return child; - - }, - - /** - * Returns the child found at the given index within this Group. - * - * @method Phaser.Group#getAt - * @memberof Phaser.Group - * @param {number} index - The index to return the child from. - * @return {*} The child that was found at the given index. - */ - getAt: function (index) { - - return this._container.getChildAt(index); - - }, - - /** - * Automatically creates a new Phaser.Sprite object and adds it to the top of this Group. - * Useful if you don't need to create the Sprite instances before-hand. - * - * @method Phaser.Group#create - * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the Group.x point. - * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the Group.y point. - * @param {string} key - The Game.cache key of the image that this Sprite will use. - * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. - * @param {boolean} [exists=true] - The default exists state of the Sprite. - * @return {Phaser.Sprite} The child that was created. - */ - create: function (x, y, key, frame, exists) { - - if (typeof exists == 'undefined') { exists = true; } - - var child = new Phaser.Sprite(this.game, x, y, key, frame); - - child.group = this; - child.exists = exists; - child.visible = exists; - child.alive = exists; - - if (child.events) - { - child.events.onAddedToGroup.dispatch(child, this); - } - - this._container.addChild(child); - - child.updateTransform(); - - if (this.cursor === null) - { - this.cursor = child; - } - - return child; - - }, - - /** - * Automatically creates multiple Phaser.Sprite objects and adds them to the top of this Group. - * Useful if you need to quickly generate a pool of identical sprites, such as bullets. By default the sprites will be set to not exist - * and will be positioned at 0, 0 (relative to the Group.x/y) - * - * @method Phaser.Group#createMultiple - * @param {number} quantity - The number of Sprites to create. - * @param {string} key - The Game.cache key of the image that this Sprite will use. - * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here. - * @param {boolean} [exists=false] - The default exists state of the Sprite. - */ - createMultiple: function (quantity, key, frame, exists) { - - if (typeof exists == 'undefined') { exists = false; } - - for (var i = 0; i < quantity; i++) - { - var child = new Phaser.Sprite(this.game, 0, 0, key, frame); - - child.group = this; - child.exists = exists; - child.visible = exists; - child.alive = exists; - - if (child.events) - { - child.events.onAddedToGroup.dispatch(child, this); - } - - this._container.addChild(child); - child.updateTransform(); - - if (this.cursor === null) - { - this.cursor = child; - } - - } - - }, - - /** - * Advances the Group cursor to the next object in the Group. If it's at the end of the Group it wraps around to the first object. - * - * @method Phaser.Group#next - */ - next: function () { - - if (this.cursor) - { - // Wrap the cursor? - if (this.cursor == this._container.last) - { - this.cursor = this._container._iNext; - } - else - { - this.cursor = this.cursor._iNext; - } - } - - }, - - /** - * Moves the Group cursor to the previous object in the Group. If it's at the start of the Group it wraps around to the last object. - * - * @method Phaser.Group#previous - */ - previous: function () { - - if (this.cursor) - { - // Wrap the cursor? - if (this.cursor == this._container._iNext) - { - this.cursor = this._container.last; - } - else - { - this.cursor = this.cursor._iPrev; - } - } - - }, - - childTest: function (prefix, child) { - - var s = prefix + ' next: '; - - if (child._iNext) - { - s = s + child._iNext.name; - } - else - { - s = s + '-null-'; - } - - s = s + ' ' + prefix + ' prev: '; - - if (child._iPrev) - { - s = s + child._iPrev.name; - } - else - { - s = s + '-null-'; - } - - console.log(s); - - }, - - swapIndex: function (index1, index2) { - - var child1 = this.getAt(index1); - var child2 = this.getAt(index2); - - console.log('swapIndex ', index1, ' with ', index2); - - this.swap(child1, child2); - - }, - - /** - * Swaps the position of two children in this Group. Both children must be in this Group. - * You cannot swap a child with itself, or swap un-parented children, doing so will return false. - * - * @method Phaser.Group#swap - * @param {*} child1 - The first child to swap. - * @param {*} child2 - The second child to swap. - * @return {boolean} True if the swap was successful, otherwise false. - */ - swap: function (child1, child2) { - - if (child1 === child2 || !child1.parent || !child2.parent || child1.group !== this || child2.group !== this) - { - return false; - } - - // Cache the values - var child1Prev = child1._iPrev; - var child1Next = child1._iNext; - var child2Prev = child2._iPrev; - var child2Next = child2._iNext; - - var endNode = this._container.last._iNext; - var currentNode = this.game.stage._stage; - - do - { - if (currentNode !== child1 && currentNode !== child2) - { - if (currentNode.first === child1) - { - currentNode.first = child2; - } - else if (currentNode.first === child2) - { - currentNode.first = child1; - } - - if (currentNode.last === child1) - { - currentNode.last = child2; - } - else if (currentNode.last === child2) - { - currentNode.last = child1; - } - } - - currentNode = currentNode._iNext; - } - while (currentNode != endNode) - - if (child1._iNext == child2) - { - // This is a downward (A to B) neighbour swap - child1._iNext = child2Next; - child1._iPrev = child2; - child2._iNext = child1; - child2._iPrev = child1Prev; - - if (child1Prev) { child1Prev._iNext = child2; } - if (child2Next) { child2Next._iPrev = child1; } - - if (child1.__renderGroup) - { - child1.__renderGroup.updateTexture(child1); - } - - if (child2.__renderGroup) - { - child2.__renderGroup.updateTexture(child2); - } - - return true; - } - else if (child2._iNext == child1) - { - // This is an upward (B to A) neighbour swap - child1._iNext = child2; - child1._iPrev = child2Prev; - child2._iNext = child1Next; - child2._iPrev = child1; - - if (child2Prev) { child2Prev._iNext = child1; } - if (child1Next) { child1Next._iPrev = child2; } - - if (child1.__renderGroup) - { - child1.__renderGroup.updateTexture(child1); - } - - if (child2.__renderGroup) - { - child2.__renderGroup.updateTexture(child2); - } - - return true; - } - else - { - // Children are far apart - child1._iNext = child2Next; - child1._iPrev = child2Prev; - child2._iNext = child1Next; - child2._iPrev = child1Prev; - - if (child1Prev) { child1Prev._iNext = child2; } - if (child1Next) { child1Next._iPrev = child2; } - if (child2Prev) { child2Prev._iNext = child1; } - if (child2Next) { child2Next._iPrev = child1; } - - if (child1.__renderGroup) - { - child1.__renderGroup.updateTexture(child1); - } - - if (child2.__renderGroup) - { - child2.__renderGroup.updateTexture(child2); - } - - return true; - } - - return false; - - }, - - /** - * Brings the given child to the top of this Group so it renders above all other children. - * - * @method Phaser.Group#bringToTop - * @param {*} child - The child to bring to the top of this Group. - * @return {*} The child that was moved. - */ - bringToTop: function (child) { - - if (child.group === this) - { - this.remove(child); - this.add(child); - } - - return child; - - }, - - /** - * Get the index position of the given child in this Group. - * - * @method Phaser.Group#getIndex - * @param {*} child - The child to get the index for. - * @return {number} The index of the child or -1 if it's not a member of this Group. - */ - getIndex: function (child) { - - return this._container.children.indexOf(child); - - }, - - /** - * Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group. - * - * @method Phaser.Group#replace - * @param {*} oldChild - The child in this Group that will be replaced. - * @param {*} newChild - The child to be inserted into this group. - */ - replace: function (oldChild, newChild) { - - if (!this._container.first._iNext) - { - return; - } - - var index = this.getIndex(oldChild); - - if (index != -1) - { - if (newChild.parent != undefined) - { - newChild.events.onRemovedFromGroup.dispatch(newChild, this); - newChild.parent.removeChild(newChild); - } - - this._container.removeChild(oldChild); - this._container.addChildAt(newChild, index); - - newChild.events.onAddedToGroup.dispatch(newChild, this); - newChild.updateTransform(); - - if (this.cursor == oldChild) - { - this.cursor = this._container._iNext; - } - } - - }, - - /** - * Sets the given property to the given value on the child. The operation controls the assignment of the value. - * - * @method Phaser.Group#setProperty - * @param {*} child - The child to set the property value on. - * @param {array} key - An array of strings that make up the property that will be set. - * @param {*} value - The value that will be set. - * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. - */ - setProperty: function (child, key, value, operation) { - - operation = operation || 0; - - // As ugly as this approach looks, and although it's limited to a depth of only 4, it's extremely fast. - // Much faster than a for loop or object iteration. There are no checks, so if the key isn't valid then it'll fail - // but as you are likely to call this from inner loops that have to perform well, I'll take that trade off. - - // 0 = Equals - // 1 = Add - // 2 = Subtract - // 3 = Multiply - // 4 = Divide - - var len = key.length; - - if (len == 1) - { - if (operation == 0) { child[key[0]] = value; } - else if (operation == 1) { child[key[0]] += value; } - else if (operation == 2) { child[key[0]] -= value; } - else if (operation == 3) { child[key[0]] *= value; } - else if (operation == 4) { child[key[0]] /= value; } - } - else if (len == 2) - { - if (operation == 0) { child[key[0]][key[1]] = value; } - else if (operation == 1) { child[key[0]][key[1]] += value; } - else if (operation == 2) { child[key[0]][key[1]] -= value; } - else if (operation == 3) { child[key[0]][key[1]] *= value; } - else if (operation == 4) { child[key[0]][key[1]] /= value; } - } - else if (len == 3) - { - if (operation == 0) { child[key[0]][key[1]][key[2]] = value; } - else if (operation == 1) { child[key[0]][key[1]][key[2]] += value; } - else if (operation == 2) { child[key[0]][key[1]][key[2]] -= value; } - else if (operation == 3) { child[key[0]][key[1]][key[2]] *= value; } - else if (operation == 4) { child[key[0]][key[1]][key[2]] /= value; } - } - else if (len == 4) - { - if (operation == 0) { child[key[0]][key[1]][key[2]][key[3]] = value; } - else if (operation == 1) { child[key[0]][key[1]][key[2]][key[3]] += value; } - else if (operation == 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; } - else if (operation == 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; } - else if (operation == 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; } - } - else - { - // TODO - Deep property scane - } - - }, - - /** - * This function allows you to quickly set the same property across all children of this Group to a new value. - * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication. - * - * @method Phaser.Group#setAll - * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x' - * @param {*} value - The value that will be set. - * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. - * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. - * @param {number} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it. - */ - setAll: function (key, value, checkAlive, checkVisible, operation) { - - key = key.split('.'); - - if (typeof checkAlive === 'undefined') { checkAlive = false; } - if (typeof checkVisible === 'undefined') { checkVisible = false; } - - operation = operation || 0; - - if (this._container.children.length > 0 && this._container.first._iNext) - { - var currentNode = this._container.first._iNext; - - do - { - if ((checkAlive == false || (checkAlive && currentNode.alive)) && (checkVisible == false || (checkVisible && currentNode.visible))) - { - this.setProperty(currentNode, key, value, operation); - } - - currentNode = currentNode._iNext; - } - while (currentNode != this._container.last._iNext) - } - - }, - - /** - * Adds the amount to the given property on all children in this Group. - * Group.addAll('x', 10) will add 10 to the child.x value. - * - * @method Phaser.Group#addAll - * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ - addAll: function (property, amount, checkAlive, checkVisible) { - - this.setAll(property, amount, checkAlive, checkVisible, 1); - - }, - - /** - * Subtracts the amount from the given property on all children in this Group. - * Group.subAll('x', 10) will minus 10 from the child.x value. - * - * @method Phaser.Group#subAll - * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ - subAll: function (property, amount, checkAlive, checkVisible) { - - this.setAll(property, amount, checkAlive, checkVisible, 2); - - }, - - /** - * Multiplies the given property by the amount on all children in this Group. - * Group.multiplyAll('x', 2) will x2 the child.x value. - * - * @method Phaser.Group#multiplyAll - * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ - multiplyAll: function (property, amount, checkAlive, checkVisible) { - - this.setAll(property, amount, checkAlive, checkVisible, 3); - - }, - - /** - * Divides the given property by the amount on all children in this Group. - * Group.divideAll('x', 2) will half the child.x value. - * - * @method Phaser.Group#divideAll - * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'. - * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50. - * @param {boolean} checkAlive - If true the property will only be changed if the child is alive. - * @param {boolean} checkVisible - If true the property will only be changed if the child is visible. - */ - divideAll: function (property, amount, checkAlive, checkVisible) { - - this.setAll(property, amount, checkAlive, checkVisible, 4); - - }, - - /** - * Calls a function on all of the children that have exists=true in this Group. - * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback. - * - * @method Phaser.Group#callAllExists - * @param {function} callback - The function that exists on the children that will be called. - * @param {boolean} existsValue - Only children with exists=existsValue will be called. - * @param {...*} parameter - Additional parameters that will be passed to the callback. - */ - callAllExists: function (callback, existsValue) { - - var args = Array.prototype.splice.call(arguments, 2); - - if (this._container.children.length > 0 && this._container.first._iNext) - { - var currentNode = this._container.first._iNext; - - do - { - if (currentNode.exists == existsValue && currentNode[callback]) - { - currentNode[callback].apply(currentNode, args); - } - - currentNode = currentNode._iNext; - } - while (currentNode != this._container.last._iNext) - - } - - }, - - /** - * Calls a function on all of the children that have exists=true in this Group. - * - * @method Phaser.Group#callbackFromArray - * @param {object} child - The object to inspect. - * @param {array} callback - The array of function names. - * @param {number} length - The size of the array (pre-calculated in callAll). - * @protected - */ - callbackFromArray: function (child, callback, length) { - - // Kinda looks like a Christmas tree - - if (length == 1) - { - if (child[callback[0]]) - { - return child[callback[0]]; - } - } - else if (length == 2) - { - if (child[callback[0]][callback[1]]) - { - return child[callback[0]][callback[1]]; - } - } - else if (length == 3) - { - if (child[callback[0]][callback[1]][callback[2]]) - { - return child[callback[0]][callback[1]][callback[2]]; - } - } - else if (length == 4) - { - if (child[callback[0]][callback[1]][callback[2]][callback[3]]) - { - return child[callback[0]][callback[1]][callback[2]][callback[3]]; - } - } - else - { - if (child[callback]) - { - return child[callback]; - } - } - - return false; - - }, - - /** - * Calls a function on all of the children regardless if they are dead or alive (see callAllExists if you need control over that) - * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child. - * - * @method Phaser.Group#callAll - * @param {string} method - A string containing the name of the function that will be called. The function must exist on the child. - * @param {string} [context=''] - A string containing the context under which the method will be executed. Leave to '' to default to the child. - * @param {...*} parameter - Additional parameters that will be passed to the method. - */ - callAll: function (method, context) { - - if (typeof method === 'undefined') - { - return; - } - - // Extract the method into an array - method = method.split('.'); - - var methodLength = method.length; - - if (typeof context === 'undefined') - { - context = null; - } - else - { - // Extract the context into an array - if (typeof context === 'string') - { - context = context.split('.'); - var contextLength = context.length; - } - } - - var args = Array.prototype.splice.call(arguments, 2); - var callback = null; - - if (this._container.children.length > 0 && this._container.first._iNext) - { - var child = this._container.first._iNext; - - do - { - callback = this.callbackFromArray(child, method, methodLength); - - if (context && callback) - { - callbackContext = this.callbackFromArray(child, context, contextLength); - - if (callback) - { - callback.apply(callbackContext, args); - } - } - else if (callback) - { - callback.apply(child, args); - } - - child = child._iNext; - } - while (child != this._container.last._iNext) - - } - - }, - - /** - * Allows you to call your own function on each member of this Group. You must pass the callback and context in which it will run. - * After the checkExists parameter you can add as many parameters as you like, which will all be passed to the callback along with the child. - * For example: Group.forEach(awardBonusGold, this, true, 100, 500) - * - * @method Phaser.Group#forEach - * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter. - * @param {Object} callbackContext - The context in which the function should be called (usually 'this'). - * @param {boolean} checkExists - If set only children with exists=true will be passed to the callback, otherwise all children will be passed. - */ - forEach: function (callback, callbackContext, checkExists) { - - if (typeof checkExists === 'undefined') - { - checkExists = false; - } - - var args = Array.prototype.splice.call(arguments, 3); - args.unshift(null); - - if (this._container.children.length > 0 && this._container.first._iNext) - { - var currentNode = this._container.first._iNext; - - do - { - if (checkExists == false || (checkExists && currentNode.exists)) - { - args[0] = currentNode; - callback.apply(callbackContext, args); - } - - currentNode = currentNode._iNext; - } - while (currentNode != this._container.last._iNext); - - } - - }, - - /** - * Allows you to call your own function on each alive member of this Group (where child.alive=true). You must pass the callback and context in which it will run. - * You can add as many parameters as you like, which will all be passed to the callback along with the child. - * For example: Group.forEachAlive(causeDamage, this, 500) - * - * @method Phaser.Group#forEachAlive - * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter. - * @param {Object} callbackContext - The context in which the function should be called (usually 'this'). - */ - forEachExists: function (callback, callbackContext) { - - var args = Array.prototype.splice.call(arguments, 2); - args.unshift(null); - - this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); - - }, - - /** - * Allows you to call your own function on each alive member of this Group (where child.alive=true). You must pass the callback and context in which it will run. - * You can add as many parameters as you like, which will all be passed to the callback along with the child. - * For example: Group.forEachAlive(causeDamage, this, 500) - * - * @method Phaser.Group#forEachAlive - * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter. - * @param {Object} callbackContext - The context in which the function should be called (usually 'this'). - */ - forEachAlive: function (callback, callbackContext) { - - var args = Array.prototype.splice.call(arguments, 2); - args.unshift(null); - - this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); - - }, - - /** - * Allows you to call your own function on each dead member of this Group (where alive=false). You must pass the callback and context in which it will run. - * You can add as many parameters as you like, which will all be passed to the callback along with the child. - * For example: Group.forEachDead(bringToLife, this) - * - * @method Phaser.Group#forEachDead - * @param {function} callback - The function that will be called. Each child of the Group will be passed to it as its first parameter. - * @param {Object} callbackContext - The context in which the function should be called (usually 'this'). - */ - forEachDead: function (callback, callbackContext) { - - var args = Array.prototype.splice.call(arguments, 2); - args.unshift(null); - - this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args); - - }, - - /** - * Call this function to sort the group according to a particular value and order. - * For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`. - * - * @method Phaser.Group#sort - * @param {string} [index='y'] - The `string` name of the property you want to sort on. - * @param {number} [order=Phaser.Group.SORT_ASCENDING] - The `Group` constant that defines the sort order. Possible values are Phaser.Group.SORT_ASCENDING and Phaser.Group.SORT_DESCENDING. - */ - sort: function (index, order) { - - if (typeof index === 'undefined') { index = 'y'; } - if (typeof order === 'undefined') { order = Phaser.Group.SORT_ASCENDING; } - - var swapped; - var temp; - - do { - - swapped = false; - - for (var i = 0, len = this._container.children.length - 1; i < len; i++) - { - if (order == Phaser.Group.SORT_ASCENDING) - { - if (this._container.children[i][index] > this._container.children[i + 1][index]) - { - this.swap(this.getAt(i), this.getAt(i + 1)); - temp = this._container.children[i]; - this._container.children[i] = this._container.children[i + 1]; - this._container.children[i + 1] = temp; - swapped = true; - } - } - else - { - if (this._container.children[i][index] < this._container.children[i + 1][index]) - { - this.swap(this.getAt(i), this.getAt(i + 1)); - temp = this._container.children[i]; - this._container.children[i] = this._container.children[i + 1]; - this._container.children[i + 1] = temp; - swapped = true; - } - } - } - } while (swapped); - - }, - - /** - * Iterates over the children of the Group. When a child has a property matching key that equals the given value, it is considered as a match. - * Matched children can be sent to the optional callback, or simply returned or counted. - * You can add as many callback parameters as you like, which will all be passed to the callback along with the child, after the callbackContext parameter. - * - * @method Phaser.Group#iterate - * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health' - * @param {any} value - If child.key === this value it will be considered a match. Note that a strict comparison is used. - * @param {number} returnType - How to return the data from this method. Either Phaser.Group.RETURN_NONE, Phaser.Group.RETURN_TOTAL or Phaser.Group.RETURN_CHILD. - * @param {function} [callback=null] - Optional function that will be called on each matching child. Each child of the Group will be passed to it as its first parameter. - * @param {Object} [callbackContext] - The context in which the function should be called (usually 'this'). - */ - iterate: function (key, value, returnType, callback, callbackContext, args) { - - if (returnType == Phaser.Group.RETURN_TOTAL && this._container.children.length == 0) - { - return -1; - } - - if (typeof callback === 'undefined') - { - callback = false; - } - - var total = 0; - - if (this._container.children.length > 0 && this._container.first._iNext) - { - var currentNode = this._container.first._iNext; - - do - { - if (currentNode[key] === value) - { - total++; - - if (callback) - { - args[0] = currentNode; - callback.apply(callbackContext, args); - } - - if (returnType == Phaser.Group.RETURN_CHILD) - { - return currentNode; - } - } - - currentNode = currentNode._iNext; - } - while (currentNode != this._container.last._iNext); - } - - if (returnType == Phaser.Group.RETURN_TOTAL) - { - return total; - } - else if (returnType == Phaser.Group.RETURN_CHILD) - { - return null; - } - - }, - - /** - * Call this function to retrieve the first object with exists == (the given state) in the Group. - * - * @method Phaser.Group#getFirstExists - * @param {boolean} state - True or false. - * @return {Any} The first child, or null if none found. - */ - getFirstExists: function (state) { - - if (typeof state !== 'boolean') - { - state = true; - } - - return this.iterate('exists', state, Phaser.Group.RETURN_CHILD); - - }, - - /** - * Call this function to retrieve the first object with alive == true in the group. - * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc. - * - * @method Phaser.Group#getFirstAlive - * @return {Any} The first alive child, or null if none found. - */ - getFirstAlive: function () { - - return this.iterate('alive', true, Phaser.Group.RETURN_CHILD); - - }, - - /** - * Call this function to retrieve the first object with alive == false in the group. - * This is handy for checking if everything has been wiped out, or choosing a squad leader, etc. - * - * @method Phaser.Group#getFirstDead - * @return {Any} The first dead child, or null if none found. - */ - getFirstDead: function () { - - return this.iterate('alive', false, Phaser.Group.RETURN_CHILD); - - }, - - /** - * Call this function to find out how many members of the group are alive. - * - * @method Phaser.Group#countLiving - * @return {number} The number of children flagged as alive. Returns -1 if Group is empty. - */ - countLiving: function () { - - return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL); - - }, - - /** - * Call this function to find out how many members of the group are dead. - * - * @method Phaser.Group#countDead - * @return {number} The number of children flagged as dead. Returns -1 if Group is empty. - */ - countDead: function () { - - return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL); - - }, - - /** - * Returns a member at random from the group. - * - * @method Phaser.Group#getRandom - * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {number} length - Optional restriction on the number of values you want to randomly select from. - * @return {Any} A random child of this Group. - */ - getRandom: function (startIndex, length) { - - if (this._container.children.length == 0) - { - return null; - } - - startIndex = startIndex || 0; - length = length || this._container.children.length; - - return this.game.math.getRandom(this._container.children, startIndex, length); - - }, - - /** - * Removes the given child from this Group and sets its group property to null. - * - * @method Phaser.Group#remove - * @param {Any} child - The child to remove. - */ - remove: function (child) { - - if (child.events) - { - child.events.onRemovedFromGroup.dispatch(child, this); - } - - this._container.removeChild(child); - - if (this.cursor == child) - { - if (this._container._iNext) - { - this.cursor = this._container._iNext; - } - else - { - this.cursor = null; - } - } - - child.group = null; - - }, - - /** - * Removes all children from this Group, setting all group properties to null. - * The Group container remains on the display list. - * - * @method Phaser.Group#removeAll - */ - removeAll: function () { - - if (this._container.children.length == 0) - { - return; - } - - do - { - if (this._container.children[0].events) - { - this._container.children[0].events.onRemovedFromGroup.dispatch(this._container.children[0], this); - } - this._container.removeChild(this._container.children[0]); - } - while (this._container.children.length > 0); - - this.cursor = null; - - }, - - /** - * Removes all children from this Group whos index falls beteen the given startIndex and endIndex values. - * - * @method Phaser.Group#removeBetween - * @param {number} startIndex - The index to start removing children from. - * @param {number} endIndex - The index to stop removing children from. Must be higher than startIndex and less than the length of the Group. - */ - removeBetween: function (startIndex, endIndex) { - - if (this._container.children.length == 0) - { - return; - } - - if (startIndex > endIndex || startIndex < 0 || endIndex > this._container.children.length) - { - return false; - } - - for (var i = startIndex; i < endIndex; i++) - { - var child = this._container.children[i]; - child.events.onRemovedFromGroup.dispatch(child, this); - this._container.removeChild(child); - - if (this.cursor == child) - { - if (this._container._iNext) - { - this.cursor = this._container._iNext; - } - else - { - this.cursor = null; - } - } - } - - }, - - /** - * Destroys this Group. Removes all children, then removes the container from the display list and nulls references. - * - * @method Phaser.Group#destroy - */ - destroy: function () { - - this.removeAll(); - - this._container.parent.removeChild(this._container); - - this._container = null; - - this.game = null; - - this.exists = false; - - this.cursor = null; - - }, - - validate: function () { - - var testObject = this.game.stage._stage.last._iNext; - var displayObject = this.game.stage._stage; - var nextObject = null; - var prevObject = null; - var count = 0; - - do - { - if (count > 0) - { - // check next - if (displayObject !== nextObject) - { - console.log('check next fail'); - return false; - } - - // check previous - if (displayObject._iPrev !== prevObject) - { - console.log('check previous fail'); - return false; - } - } - - // Set the next object - nextObject = displayObject._iNext; - prevObject = displayObject; - - displayObject = displayObject._iNext; - - count++; - - } - while(displayObject != testObject) - - return true; - - }, - - /** - * Dumps out a list of Group children and their index positions to the browser console. Useful for group debugging. - * - * @method Phaser.Group#dump - * @param {boolean} [full=false] - If full the dump will include the entire display list, start from the Stage. Otherwise it will only include this container. - */ - dump: function (full) { - - if (typeof full == 'undefined') - { - full = false; - } - - var spacing = 20; - var output = "\n" + Phaser.Utils.pad('Node', spacing) + "|" + Phaser.Utils.pad('Next', spacing) + "|" + Phaser.Utils.pad('Previous', spacing) + "|" + Phaser.Utils.pad('First', spacing) + "|" + Phaser.Utils.pad('Last', spacing); - - console.log(output); - - var output = Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing); - console.log(output); - - if (full) - { - var testObject = this.game.stage._stage.last._iNext; - var displayObject = this.game.stage._stage; - } - else - { - var testObject = this._container.last._iNext; - var displayObject = this._container; - } - - do - { - var name = displayObject.name || '*'; - - if (this.cursor == displayObject) - { - var name = '> ' + name; - } - - var nameNext = '-'; - var namePrev = '-'; - var nameFirst = '-'; - var nameLast = '-'; - - if (displayObject._iNext) - { - nameNext = displayObject._iNext.name; - } - - if (displayObject._iPrev) - { - namePrev = displayObject._iPrev.name; - } - - if (displayObject.first) - { - nameFirst = displayObject.first.name; - } - - if (displayObject.last) - { - nameLast = displayObject.last.name; - } - - if (typeof nameNext === 'undefined') - { - nameNext = '-'; - } - - if (typeof namePrev === 'undefined') - { - namePrev = '-'; - } - - if (typeof nameFirst === 'undefined') - { - nameFirst = '-'; - } - - if (typeof nameLast === 'undefined') - { - nameLast = '-'; - } - - var output = Phaser.Utils.pad(name, spacing) + "|" + Phaser.Utils.pad(nameNext, spacing) + "|" + Phaser.Utils.pad(namePrev, spacing) + "|" + Phaser.Utils.pad(nameFirst, spacing) + "|" + Phaser.Utils.pad(nameLast, spacing); - console.log(output); - - displayObject = displayObject._iNext; - - } - while(displayObject != testObject) - - } - -}; - -/** -* @name Phaser.Group#total -* @property {number} total - The total number of children in this Group, regardless of their alive state. -* @readonly -*/ -Object.defineProperty(Phaser.Group.prototype, "total", { - - get: function () { - return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); - // return this._container.children.length; - } - -}); - -/** -* @name Phaser.Group#length -* @property {number} length - The number of children in this Group. -* @readonly -*/ -Object.defineProperty(Phaser.Group.prototype, "length", { - - get: function () { - return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL); - // return this._container.children.length; - } - -}); - -/** -* The x coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates. -* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#x -* @property {number} x - The x coordinate of the Group container. -*/ -Object.defineProperty(Phaser.Group.prototype, "x", { - - get: function () { - return this._container.position.x; - }, - - set: function (value) { - this._container.position.x = value; - } - -}); - -/** -* The y coordinate of the Group container. You can adjust the Group container itself by modifying its coordinates. -* This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#y -* @property {number} y - The y coordinate of the Group container. -*/ -Object.defineProperty(Phaser.Group.prototype, "y", { - - get: function () { - return this._container.position.y; - }, - - set: function (value) { - this._container.position.y = value; - } - -}); - -/** -* The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation. -* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#angle -* @property {number} angle - The angle of rotation given in degrees, where 0 degrees = to the right. -*/ -Object.defineProperty(Phaser.Group.prototype, "angle", { - - get: function() { - return Phaser.Math.radToDeg(this._container.rotation); - }, - - set: function(value) { - this._container.rotation = Phaser.Math.degToRad(value); - } - -}); - -/** -* The angle of rotation of the Group container. This will adjust the Group container itself by modifying its rotation. -* This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position. -* @name Phaser.Group#rotation -* @property {number} rotation - The angle of rotation given in radians. -*/ -Object.defineProperty(Phaser.Group.prototype, "rotation", { - - get: function () { - return this._container.rotation; - }, - - set: function (value) { - this._container.rotation = value; - } - -}); - -/** -* @name Phaser.Group#visible -* @property {boolean} visible - The visible state of the Group. Non-visible Groups and all of their children are not rendered. -*/ -Object.defineProperty(Phaser.Group.prototype, "visible", { - - get: function () { - return this._container.visible; - }, - - set: function (value) { - this._container.visible = value; - } - -}); - -/** -* @name Phaser.Group#alpha -* @property {number} alpha - The alpha value of the Group container. -*/ -Object.defineProperty(Phaser.Group.prototype, "alpha", { - - get: function () { - return this._container.alpha; - }, - - set: function (value) { - this._container.alpha = value; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* "This world is but a canvas to our imagination." - Henry David Thoreau -* -* A game has only one world. The world is an abstract place in which all game objects live. It is not bound -* by stage limits and can be any size. You look into the world via cameras. All game objects live within -* the world at world-based coordinates. By default a world is created the same size as your Stage. -* -* @class Phaser.World -* @constructor -* @param {Phaser.Game} game - Reference to the current game instance. -*/ -Phaser.World = function (game) { - - Phaser.Group.call(this, game, null, '__world', false); - - /** - * @property {Phaser.Point} scale - Replaces the PIXI.Point with a slightly more flexible one. - */ - this.scale = new Phaser.Point(1, 1); - - /** - * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects. - * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display. - * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0. - * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0. - * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from. - */ - this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height); - - /** - * @property {Phaser.Camera} camera - Camera instance. - */ - this.camera = null; - - /** - * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated. - */ - this.currentRenderOrderID = 0; - -}; - -Phaser.World.prototype = Object.create(Phaser.Group.prototype); -Phaser.World.prototype.constructor = Phaser.World; - -/** -* Initialises the game world. -* -* @method Phaser.World#boot -* @protected -*/ -Phaser.World.prototype.boot = function () { - - this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height); - - this.camera.displayObject = this._container; - - this.game.camera = this.camera; - -} - -/** -* This is called automatically every frame, and is where main logic happens. -* -* @method Phaser.World#update -*/ -Phaser.World.prototype.update = function () { - - this.currentRenderOrderID = 0; - - if (this.game.stage._stage.first._iNext) - { - var currentNode = this.game.stage._stage.first._iNext; - var skipChildren; - - do - { - skipChildren = false; - - if (currentNode['preUpdate']) - { - skipChildren = (currentNode.preUpdate() === false); - } - - if (currentNode['update']) - { - skipChildren = (currentNode.update() === false) || skipChildren; - } - - if (skipChildren) - { - currentNode = currentNode.last._iNext; - } - else - { - currentNode = currentNode._iNext; - } - - } - while (currentNode != this.game.stage._stage.last._iNext) - } - -} - -/** -* This is called automatically every frame, and is where main logic happens. -* @method Phaser.World#postUpdate -*/ -Phaser.World.prototype.postUpdate = function () { - - this.camera.update(); - - if (this.game.stage._stage.first._iNext) - { - var currentNode = this.game.stage._stage.first._iNext; - - do - { - if (currentNode['postUpdate']) - { - currentNode.postUpdate(); - } - - currentNode = currentNode._iNext; - } - while (currentNode != this.game.stage._stage.last._iNext) - } - -} - -/** -* Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height. -* If you need to adjust the bounds of the world -* @method Phaser.World#setBounds -* @param {number} x - Top left most corner of the world. -* @param {number} y - Top left most corner of the world. -* @param {number} width - New width of the world. -* @param {number} height - New height of the world. -*/ -Phaser.World.prototype.setBounds = function (x, y, width, height) { - - this.bounds.setTo(x, y, width, height); - - if (this.camera.bounds) - { - this.camera.bounds.setTo(x, y, width, height); - } - -} - -/** -* Destroyer of worlds. -* @method Phaser.World#destroy -*/ -Phaser.World.prototype.destroy = function () { - - this.camera.x = 0; - this.camera.y = 0; - - this.game.input.reset(true); - - this.removeAll(); - -} - -/** -* @name Phaser.World#width -* @property {number} width - Gets or sets the current width of the game world. -*/ -Object.defineProperty(Phaser.World.prototype, "width", { - - get: function () { - return this.bounds.width; - }, - - set: function (value) { - this.bounds.width = value; - } - -}); - -/** -* @name Phaser.World#height -* @property {number} height - Gets or sets the current height of the game world. -*/ -Object.defineProperty(Phaser.World.prototype, "height", { - - get: function () { - return this.bounds.height; - }, - - set: function (value) { - this.bounds.height = value; - } - -}); - -/** -* @name Phaser.World#centerX -* @property {number} centerX - Gets the X position corresponding to the center point of the world. -* @readonly -*/ -Object.defineProperty(Phaser.World.prototype, "centerX", { - - get: function () { - return this.bounds.halfWidth; - } - -}); - -/** -* @name Phaser.World#centerY -* @property {number} centerY - Gets the Y position corresponding to the center point of the world. -* @readonly -*/ -Object.defineProperty(Phaser.World.prototype, "centerY", { - - get: function () { - return this.bounds.halfHeight; - } - -}); - -/** -* @name Phaser.World#randomX -* @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world. -* @readonly -*/ -Object.defineProperty(Phaser.World.prototype, "randomX", { - - get: function () { - - if (this.bounds.x < 0) - { - return this.game.rnd.integerInRange(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x))); - } - else - { - return this.game.rnd.integerInRange(this.bounds.x, this.bounds.width); - } - - } - -}); - -/** -* @name Phaser.World#randomY -* @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world. -* @readonly -*/ -Object.defineProperty(Phaser.World.prototype, "randomY", { - - get: function () { - - if (this.bounds.y < 0) - { - return this.game.rnd.integerInRange(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y))); - } - else - { - return this.game.rnd.integerInRange(this.bounds.y, this.bounds.height); - } - - } - -}); - -/** -* @name Phaser.World#visible -* @property {boolean} visible - Gets or sets the visible state of the World. -*/ -Object.defineProperty(Phaser.World.prototype, "visible", { - - get: function () { - return this._container.visible; - }, - - set: function (value) { - this._container.visible = value; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Game constructor -* -* Instantiate a new Phaser.Game object. -* @class Phaser.Game -* @classdesc This is where the magic happens. The Game object is the heart of your game, -* providing quick access to common functions and handling the boot process. -* "Hell, there are no rules here - we're trying to accomplish something." -* Thomas A. Edison -* @constructor -* @param {number} [width=800] - The width of your game in game pixels. -* @param {number} [height=600] - The height of your game in game pixels. -* @param {number} [renderer=Phaser.AUTO] - Which renderer to use (canvas or webgl) -* @param {HTMLElement} [parent=''] - The Games DOM parent. -* @param {any} [state=null] - Description. -* @param {boolean} [transparent=false] - Use a transparent canvas background or not. -* @param {boolean} [antialias=true] - Anti-alias graphics. -*/ -Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias) { - - width = width || 800; - height = height || 600; - renderer = renderer || Phaser.AUTO; - parent = parent || ''; - state = state || null; - - if (typeof transparent == 'undefined') { transparent = false; } - if (typeof antialias == 'undefined') { antialias = true; } - - /** - * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances). - */ - this.id = Phaser.GAMES.push(this) - 1; - - /** - * @property {HTMLElement} parent - The Games DOM parent. - */ - this.parent = parent; - - // Do some more intelligent size parsing here, so they can set "100%" for example, maybe pass the scale mode in here too? - - /** - * @property {number} width - The Game width (in pixels). - */ - this.width = width; - - /** - * @property {number} height - The Game height (in pixels). - */ - this.height = height; - - /** - * @property {boolean} transparent - Use a transparent canvas background or not. - */ - this.transparent = transparent; - - /** - * @property {boolean} antialias - Anti-alias graphics (in WebGL this helps with edges, in Canvas2D it retains pixel-art quality). - */ - this.antialias = antialias; - - /** - * @property {number} renderer - The Pixi Renderer - * @default - */ - this.renderer = null; - - /** - * @property {number} state - The StateManager. - */ - this.state = new Phaser.StateManager(this, state); - - /** - * @property {boolean} _paused - Is game paused? - * @private - * @default - */ - this._paused = false; - - /** - * @property {number} renderType - The Renderer this Phaser.Game will use. Either Phaser.RENDERER_AUTO, Phaser.RENDERER_CANVAS or Phaser.RENDERER_WEBGL. - */ - this.renderType = renderer; - - /** - * @property {boolean} _loadComplete - Whether load complete loading or not. - * @private - * @default - */ - this._loadComplete = false; - - /** - * @property {boolean} isBooted - Whether the game engine is booted, aka available. - * @default - */ - this.isBooted = false; - - /** - * @property {boolean} id -Is game running or paused? - * @default - */ - this.isRunning = false; - - /** - * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout - * @default - */ - this.raf = null; - - /** - * @property {Phaser.GameObjectFactory} add - Reference to the GameObject Factory. - * @default - */ - this.add = null; - - /** - * @property {Phaser.Cache} cache - Reference to the assets cache. - * @default - */ - this.cache = null; - - /** - * @property {Phaser.Input} input - Reference to the input manager - * @default - */ - this.input = null; - - /** - * @property {Phaser.Loader} load - Reference to the assets loader. - * @default - */ - this.load = null; - - /** - * @property {Phaser.Math} math - Reference to the math helper. - * @default - */ - this.math = null; - - /** - * @property {Phaser.Net} net - Reference to the network class. - * @default - */ - this.net = null; - - /** - * @property {Phaser.SoundManager} sound - Reference to the sound manager. - * @default - */ - this.sound = null; - - /** - * @property {Phaser.Stage} stage - Reference to the stage. - * @default - */ - this.stage = null; - - /** - * @property {Phaser.TimeManager} time - Reference to game clock. - * @default - */ - this.time = null; - - /** - * @property {Phaser.TweenManager} tweens - Reference to the tween manager. - * @default - */ - this.tweens = null; - - /** - * @property {Phaser.World} world - Reference to the world. - * @default - */ - this.world = null; - - /** - * @property {Phaser.Physics.PhysicsManager} physics - Reference to the physics manager. - * @default - */ - this.physics = null; - - /** - * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper. - * @default - */ - this.rnd = null; - - /** - * @property {Phaser.Device} device - Contains device information and capabilities. - * @default - */ - this.device = null; - - /** - * @property {Phaser.Physics.PhysicsManager} camera - A handy reference to world.camera. - * @default - */ - this.camera = null; - - /** - * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view. - * @default - */ - this.canvas = null; - - /** - * @property {Context} context - A handy reference to renderer.context (only set for CANVAS games) - * @default - */ - this.context = null; - - /** - * @property {Phaser.Utils.Debug} debug - A set of useful debug utilitie. - * @default - */ - this.debug = null; - - /** - * @property {Phaser.Particles} particles - The Particle Manager. - * @default - */ - this.particles = null; - - var _this = this; - - this._onBoot = function () { - return _this.boot(); - } - - if (document.readyState === 'complete' || document.readyState === 'interactive') - { - window.setTimeout(this._onBoot, 0); - } - else - { - document.addEventListener('DOMContentLoaded', this._onBoot, false); - window.addEventListener('load', this._onBoot, false); - } - - return this; - -}; - -Phaser.Game.prototype = { - - /** - * Initialize engine sub modules and start the game. - * - * @method Phaser.Game#boot - * @protected - */ - boot: function () { - - if (this.isBooted) - { - return; - } - - if (!document.body) - { - window.setTimeout(this._onBoot, 20); - } - else - { - document.removeEventListener('DOMContentLoaded', this._onBoot); - window.removeEventListener('load', this._onBoot); - - this.onPause = new Phaser.Signal; - this.onResume = new Phaser.Signal; - - this.isBooted = true; - - this.device = new Phaser.Device(); - this.math = Phaser.Math; - this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]); - - this.stage = new Phaser.Stage(this, this.width, this.height); - - this.setUpRenderer(); - - this.world = new Phaser.World(this); - this.add = new Phaser.GameObjectFactory(this); - this.cache = new Phaser.Cache(this); - this.load = new Phaser.Loader(this); - this.time = new Phaser.Time(this); - this.tweens = new Phaser.TweenManager(this); - this.input = new Phaser.Input(this); - this.sound = new Phaser.SoundManager(this); - this.physics = new Phaser.Physics.Arcade(this); - this.particles = new Phaser.Particles(this); - this.plugins = new Phaser.PluginManager(this, this); - this.net = new Phaser.Net(this); - this.debug = new Phaser.Utils.Debug(this); - - this.stage.boot(); - this.world.boot(); - this.input.boot(); - this.sound.boot(); - this.state.boot(); - - this.load.onLoadComplete.add(this.loadComplete, this); - - this.showDebugHeader(); - - this.isRunning = true; - this._loadComplete = false; - - this.raf = new Phaser.RequestAnimationFrame(this); - this.raf.start(); - - } - - }, - - /** - * Displays a Phaser version debug header in the console. - * - * @method Phaser.Game#showDebugHeader - * @protected - */ - showDebugHeader: function () { - - var v = Phaser.DEV_VERSION; - var r = 'Canvas'; - var a = 'HTML Audio'; - - if (this.renderType == Phaser.WEBGL) - { - r = 'WebGL'; - } - - if (this.device.webAudio) - { - a = 'WebAudio'; - } - - if (this.device.chrome) - { - var args = [ - '%c %c %c Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a + ' %c %c ', - 'background: #00bff3', - 'background: #0072bc', - 'color: #ffffff; background: #003471', - 'background: #0072bc', - 'background: #00bff3' - ]; - - console.log.apply(console, args); - } - else - { - console.log('Phaser v' + v + ' - Renderer: ' + r + ' - Audio: ' + a); - } - - }, - - /** - * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not. - * - * @method Phaser.Game#setUpRenderer - * @protected - */ - setUpRenderer: function () { - - if (this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && this.device.webGL == false)) - { - if (this.device.canvas) - { - this.renderType = Phaser.CANVAS; - this.renderer = new PIXI.CanvasRenderer(this.width, this.height, this.stage.canvas, this.transparent); - Phaser.Canvas.setSmoothingEnabled(this.renderer.context, this.antialias); - this.canvas = this.renderer.view; - this.context = this.renderer.context; - } - else - { - throw new Error('Phaser.Game - cannot create Canvas or WebGL context, aborting.'); - } - } - else - { - // They requested WebGL, and their browser supports it - this.renderType = Phaser.WEBGL; - this.renderer = new PIXI.WebGLRenderer(this.width, this.height, this.stage.canvas, this.transparent, this.antialias); - this.canvas = this.renderer.view; - this.context = null; - } - - Phaser.Canvas.addToDOM(this.renderer.view, this.parent, true); - Phaser.Canvas.setTouchAction(this.renderer.view); - - }, - - /** - * Called when the load has finished, after preload was run. - * - * @method Phaser.Game#loadComplete - * @protected - */ - loadComplete: function () { - - this._loadComplete = true; - - this.state.loadComplete(); - - }, - - /** - * The core game loop. - * - * @method Phaser.Game#update - * @protected - * @param {number} time - The current time as provided by RequestAnimationFrame. - */ - update: function (time) { - - this.time.update(time); - - if (this._paused) - { - this.renderer.render(this.stage._stage); - this.plugins.render(); - this.state.render(); - } - else - { - this.plugins.preUpdate(); - this.physics.preUpdate(); - - this.stage.update(); - this.input.update(); - this.tweens.update(); - this.sound.update(); - this.world.update(); - this.particles.update(); - this.state.update(); - this.plugins.update(); - - this.world.postUpdate(); - this.plugins.postUpdate(); - - this.renderer.render(this.stage._stage); - this.plugins.render(); - this.state.render(); - - this.plugins.postRender(); - } - - }, - - /** - * Nuke the entire game from orbit - * - * @method Phaser.Game#destroy - */ - destroy: function () { - - this.raf.stop(); - - this.input.destroy(); - - this.state.destroy(); - - this.state = null; - this.cache = null; - this.input = null; - this.load = null; - this.sound = null; - this.stage = null; - this.time = null; - this.world = null; - this.isBooted = false; - - } - -}; - -/** -* The paused state of the Game. A paused game doesn't update any of its subsystems. -* When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched. -* @name Phaser.Game#paused -* @property {boolean} paused - Gets and sets the paused state of the Game. -*/ -Object.defineProperty(Phaser.Game.prototype, "paused", { - - get: function () { - return this._paused; - }, - - set: function (value) { - - if (value === true) - { - if (this._paused == false) - { - this._paused = true; - this.onPause.dispatch(this); - } - } - else - { - if (this._paused) - { - this._paused = false; - this.onResume.dispatch(this); - } - } - - } - -}); - -/** -* "Deleted code is debugged code." - Jeff Sickel -*/ - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Constructor for Phaser Input. -* @class Phaser.Input -* @classdesc A game specific Input manager that looks after the mouse, keyboard and touch objects. -* This is updated by the core game loop. -* @constructor -* @param {Phaser.Game} game - Current game instance. -*/ -Phaser.Input = function (game) { - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {Description} hitCanvas - Description. - * @default - */ - this.hitCanvas = null; - - /** - * @property {Description} hitContext - Description. - * @default - */ - this.hitContext = null; - -}; - -/** -* @constant -* @type {number} -*/ -Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0; - -/** -* @constant -* @type {number} -*/ -Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1; - -/** -* @constant -* @type {number} -*/ -Phaser.Input.MOUSE_TOUCH_COMBINE = 2; - -Phaser.Input.prototype = { - - /** - * @property {Phaser.Game} game - */ - game: null, - - /** - * How often should the input pointers be checked for updates? - * A value of 0 means every single frame (60fps), a value of 1 means every other frame (30fps) and so on. - * @property {number} pollRate - * @default - */ - pollRate: 0, - - /** - * @property {number} _pollCounter - Description. - * @private - * @default - */ - _pollCounter: 0, - - /** - * A vector object representing the previous position of the Pointer. - * @property {Vec2} vector - * @private - * @default - */ - _oldPosition: null, - - /** - * X coordinate of the most recent Pointer event - * @property {number} _x - * @private - * @default - */ - _x: 0, - - /** - * Y coordinate of the most recent Pointer event - * @property {number} _y - * @private - * @default - */ - _y: 0, - - /** - * You can disable all Input by setting Input.disabled: true. While set all new input related events will be ignored. - * If you need to disable just one type of input, for example mouse, use Input.mouse.disabled: true instead - * @property {boolean} disabled - * @default - */ - disabled: false, - - /** - * Controls the expected behaviour when using a mouse and touch together on a multi-input device. - * @property {Description} multiInputOverride - */ - multiInputOverride: Phaser.Input.MOUSE_TOUCH_COMBINE, - - /** - * A vector object representing the current position of the Pointer. - * @property {Phaser.Point} position - * @default - */ - position: null, - - /** - * A vector object representing the speed of the Pointer. Only really useful in single Pointer games, - * otherwise see the Pointer objects directly. - * @property {Phaser.Point} speed - * @default - */ - speed: null, - - /** - * A Circle object centered on the x/y screen coordinates of the Input. - * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything. - * @property {Phaser.Circle} circle - * @default - */ - circle: null, - - /** - * The scale by which all input coordinates are multiplied, calculated by the StageScaleMode. - * In an un-scaled game the values will be x: 1 and y: 1. - * @property {Phaser.Point} scale - * @default - */ - scale: null, - - /** - * The maximum number of Pointers allowed to be active at any one time. - * For lots of games it's useful to set this to 1. - * @property {number} maxPointers - * @default - */ - maxPointers: 10, - - /** - * The current number of active Pointers. - * @property {number} currentPointers - * @default - */ - currentPointers: 0, - - /** - * The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or clicke - * @property {number} tapRate - * @default - */ - tapRate: 200, - - /** - * The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click - * @property {number} doubleTapRate - * @default - */ - doubleTapRate: 300, - - /** - * The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event - * @property {number} holdRate - * @default - */ - holdRate: 2000, - - /** - * The number of milliseconds below which the Pointer is considered justPressed - * @property {number} justPressedRate - * @default - */ - justPressedRate: 200, - - /** - * The number of milliseconds below which the Pointer is considered justReleased - * @property {number} justReleasedRate - * @default - */ - justReleasedRate: 200, - - /** - * Sets if the Pointer objects should record a history of x/y coordinates they have passed through. - * The history is cleared each time the Pointer is pressed down. - * The history is updated at the rate specified in Input.pollRate - * @property {boolean} recordPointerHistory - * @default - */ - recordPointerHistory: false, - - /** - * The rate in milliseconds at which the Pointer objects should update their tracking history - * @property {number} recordRate - * @default - */ - recordRate: 100, - - /** - * The total number of entries that can be recorded into the Pointer objects tracking history. - * If the Pointer is tracking one event every 100ms, then a trackLimit of 100 would store the last 10 seconds worth of history. - * @property {number} recordLimit - * @default - */ - recordLimit: 100, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer1 - */ - pointer1: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer2 - */ - pointer2: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer3 - */ - pointer3: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer4 - */ - pointer4: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer5 - */ - pointer5: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer6 - */ - pointer6: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer7 - */ - pointer7: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer8 - */ - pointer8: null, - - /** - * A Pointer object - * @property {Phaser.Pointer} pointer9 - */ - pointer9: null, - - /** - * A Pointer object. - * @property {Phaser.Pointer} pointer10 - */ - pointer10: null, - - /** - * The most recently active Pointer object. - * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse. - * @property {Phaser.Pointer} activePointer - * @default - */ - activePointer: null, - - /** - * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game. - * @property {Pointer} mousePointer - * @default - */ - mousePointer: null, - - /** - * The Mouse Input manager. - * @property {Phaser.Mouse} mouse - The Mouse Input manager. - * @default - */ - mouse: null, - - /** - * The Keyboard Input manager. - * @property {Phaser.Keyboard} keyboard - The Keyboard Input manager. - * @default - */ - keyboard: null, - - /** - * The Touch Input manager. - * @property {Phaser.Touch} touch - the Touch Input manager. - * @default - */ - touch: null, - - /** - * The MSPointer Input manager. - * @property {Phaser.MSPointer} mspointer - The MSPointer Input manager. - * @default - */ - mspointer: null, - - /** - * A Signal that is dispatched each time a pointer is pressed down. - * @property {Phaser.Signal} onDown - * @default - */ - onDown: null, - - /** - * A Signal that is dispatched each time a pointer is released. - * @property {Phaser.Signal} onUp - * @default - */ - onUp: null, - - /** - * A Signal that is dispatched each time a pointer is tapped. - * @property {Phaser.Signal} onTap - * @default - */ - onTap: null, - - /** - * A Signal that is dispatched each time a pointer is held down. - * @property {Phaser.Signal} onHold - * @default - */ - onHold: null, - - /** - * A linked list of interactive objects, the InputHandler components (belonging to Sprites) register themselves with this. - * @property {Phaser.LinkedList} interactiveItems - */ - interactiveItems: new Phaser.LinkedList(), - - /** - * Starts the Input Manager running. - * @method Phaser.Input#boot - * @protected - */ - boot: function () { - - this.mousePointer = new Phaser.Pointer(this.game, 0); - this.pointer1 = new Phaser.Pointer(this.game, 1); - this.pointer2 = new Phaser.Pointer(this.game, 2); - - this.mouse = new Phaser.Mouse(this.game); - this.keyboard = new Phaser.Keyboard(this.game); - this.touch = new Phaser.Touch(this.game); - this.mspointer = new Phaser.MSPointer(this.game); - - this.onDown = new Phaser.Signal(); - this.onUp = new Phaser.Signal(); - this.onTap = new Phaser.Signal(); - this.onHold = new Phaser.Signal(); - - this.scale = new Phaser.Point(1, 1); - this.speed = new Phaser.Point(); - this.position = new Phaser.Point(); - this._oldPosition = new Phaser.Point(); - - this.circle = new Phaser.Circle(0, 0, 44); - - this.activePointer = this.mousePointer; - this.currentPointers = 0; - - this.hitCanvas = document.createElement('canvas'); - this.hitCanvas.width = 1; - this.hitCanvas.height = 1; - this.hitContext = this.hitCanvas.getContext('2d'); - - this.mouse.start(); - this.keyboard.start(); - this.touch.start(); - this.mspointer.start(); - this.mousePointer.active = true; - - }, - - /** - * Stops all of the Input Managers from running. - * @method Phaser.Input#destroy - */ - destroy: function () { - - this.mouse.stop(); - this.keyboard.stop(); - this.touch.stop(); - this.mspointer.stop(); - - }, - - /** - * Add a new Pointer object to the Input Manager. By default Input creates 3 pointer objects: mousePointer, pointer1 and pointer2. - * If you need more then use this to create a new one, up to a maximum of 10. - * @method Phaser.Input#addPointer - * @return {Phaser.Pointer} A reference to the new Pointer object that was created. - */ - addPointer: function () { - - var next = 0; - - for (var i = 10; i > 0; i--) - { - if (this['pointer' + i] === null) - { - next = i; - } - } - - if (next == 0) - { - console.warn("You can only have 10 Pointer objects"); - return null; - } - else - { - this['pointer' + next] = new Phaser.Pointer(this.game, next); - return this['pointer' + next]; - } - - }, - - /** - * Updates the Input Manager. Called by the core Game loop. - * @method Phaser.Input#update - * @protected - */ - update: function () { - - if (this.pollRate > 0 && this._pollCounter < this.pollRate) - { - this._pollCounter++; - return; - } - - this.speed.x = this.position.x - this._oldPosition.x; - this.speed.y = this.position.y - this._oldPosition.y; - - this._oldPosition.copyFrom(this.position); - this.mousePointer.update(); - - this.pointer1.update(); - this.pointer2.update(); - - if (this.pointer3) { this.pointer3.update(); } - if (this.pointer4) { this.pointer4.update(); } - if (this.pointer5) { this.pointer5.update(); } - if (this.pointer6) { this.pointer6.update(); } - if (this.pointer7) { this.pointer7.update(); } - if (this.pointer8) { this.pointer8.update(); } - if (this.pointer9) { this.pointer9.update(); } - if (this.pointer10) { this.pointer10.update(); } - - this._pollCounter = 0; - }, - - /** - * Reset all of the Pointers and Input states - * @method Phaser.Input#reset - * @param {boolean} hard - A soft reset (hard = false) won't reset any Signals that might be bound. A hard reset will. - */ - reset: function (hard) { - - if (this.game.isBooted == false) - { - return; - } - - if (typeof hard == 'undefined') { hard = false; } - - this.keyboard.reset(); - this.mousePointer.reset(); - - for (var i = 1; i <= 10; i++) - { - if (this['pointer' + i]) - { - this['pointer' + i].reset(); - } - } - - this.currentPointers = 0; - this.game.stage.canvas.style.cursor = "default"; - - if (hard == true) - { - this.onDown.dispose(); - this.onUp.dispose(); - this.onTap.dispose(); - this.onHold.dispose(); - this.onDown = new Phaser.Signal(); - this.onUp = new Phaser.Signal(); - this.onTap = new Phaser.Signal(); - this.onHold = new Phaser.Signal(); - - this.interactiveItems.callAll('reset'); - } - - this._pollCounter = 0; - - }, - - /** - * Resets the speed and old position properties. - * @method Phaser.Input#resetSpeed - * @param {number} x - Sets the oldPosition.x value. - * @param {number} y - Sets the oldPosition.y value. - */ - resetSpeed: function (x, y) { - - this._oldPosition.setTo(x, y); - this.speed.setTo(0, 0); - - }, - - /** - * Find the first free Pointer object and start it, passing in the event data. This is called automatically by Phaser.Touch and Phaser.MSPointer. - * @method Phaser.Input#startPointer - * @param {Any} event - The event data from the Touch event. - * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available. - */ - startPointer: function (event) { - - if (this.maxPointers < 10 && this.totalActivePointers == this.maxPointers) - { - return null; - } - - if (this.pointer1.active == false) - { - return this.pointer1.start(event); - } - else if (this.pointer2.active == false) - { - return this.pointer2.start(event); - } - else - { - for (var i = 3; i <= 10; i++) - { - if (this['pointer' + i] && this['pointer' + i].active == false) - { - return this['pointer' + i].start(event); - } - } - } - - return null; - - }, - - /** - * Updates the matching Pointer object, passing in the event data. This is called automatically and should not normally need to be invoked. - * @method Phaser.Input#updatePointer - * @param {Any} event - The event data from the Touch event. - * @return {Phaser.Pointer} The Pointer object that was updated or null if no Pointer object is available. - */ - updatePointer: function (event) { - - if (this.pointer1.active && this.pointer1.identifier == event.identifier) - { - return this.pointer1.move(event); - } - else if (this.pointer2.active && this.pointer2.identifier == event.identifier) - { - return this.pointer2.move(event); - } - else - { - for (var i = 3; i <= 10; i++) - { - if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier) - { - return this['pointer' + i].move(event); - } - } - } - - return null; - - }, - - /** - * Stops the matching Pointer object, passing in the event data. - * @method Phaser.Input#stopPointer - * @param {Any} event - The event data from the Touch event. - * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available. - */ - stopPointer: function (event) { - - if (this.pointer1.active && this.pointer1.identifier == event.identifier) - { - return this.pointer1.stop(event); - } - else if (this.pointer2.active && this.pointer2.identifier == event.identifier) - { - return this.pointer2.stop(event); - } - else - { - for (var i = 3; i <= 10; i++) - { - if (this['pointer' + i] && this['pointer' + i].active && this['pointer' + i].identifier == event.identifier) - { - return this['pointer' + i].stop(event); - } - } - } - - return null; - - }, - - /** - * Get the next Pointer object whos active property matches the given state - * @method Phaser.Input#getPointer - * @param {boolean} state - The state the Pointer should be in (false for inactive, true for active). - * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state. - */ - getPointer: function (state) { - - state = state || false; - - if (this.pointer1.active == state) - { - return this.pointer1; - } - else if (this.pointer2.active == state) - { - return this.pointer2; - } - else - { - for (var i = 3; i <= 10; i++) - { - if (this['pointer' + i] && this['pointer' + i].active == state) - { - return this['pointer' + i]; - } - } - } - - return null; - - }, - - /** - * Get the Pointer object whos identified property matches the given identifier value. - * @method Phaser.Input#getPointerFromIdentifier - * @param {number} identifier - The Pointer.identifier value to search for. - * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier. - */ - getPointerFromIdentifier: function (identifier) { - - if (this.pointer1.identifier == identifier) - { - return this.pointer1; - } - else if (this.pointer2.identifier == identifier) - { - return this.pointer2; - } - else - { - for (var i = 3; i <= 10; i++) - { - if (this['pointer' + i] && this['pointer' + i].identifier == identifier) - { - return this['pointer' + i]; - } - } - } - - return null; - - } - -}; - -/** -* The X coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values. -* @name Phaser.Input#x -* @property {number} x - The X coordinate of the most recently active pointer. -*/ -Object.defineProperty(Phaser.Input.prototype, "x", { - - get: function () { - return this._x; - }, - - set: function (value) { - this._x = Math.floor(value); - } - -}); - -/** -* The Y coordinate of the most recently active pointer. This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values. -* @name Phaser.Input#y -* @property {number} y - The Y coordinate of the most recently active pointer. -*/ -Object.defineProperty(Phaser.Input.prototype, "y", { - - get: function () { - return this._y; - }, - - set: function (value) { - this._y = Math.floor(value); - } - -}); - -/** -* @name Phaser.Input#pollLocked -* @property {boolean} pollLocked - True if the Input is currently poll rate locked. -* @readonly -*/ -Object.defineProperty(Phaser.Input.prototype, "pollLocked", { - - get: function () { - return (this.pollRate > 0 && this._pollCounter < this.pollRate); - } - -}); - -/** -* The total number of inactive Pointers -* @name Phaser.Input#totalInactivePointers -* @property {number} totalInactivePointers - The total number of inactive Pointers. -* @readonly -*/ -Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", { - - get: function () { - return 10 - this.currentPointers; - } - -}); - -/** -* The total number of active Pointers -* @name Phaser.Input#totalActivePointers -* @property {number} totalActivePointers - The total number of active Pointers. -* @readonly -*/ -Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", { - - get: function () { - - this.currentPointers = 0; - - for (var i = 1; i <= 10; i++) - { - if (this['pointer' + i] && this['pointer' + i].active) - { - this.currentPointers++; - } - } - - return this.currentPointers; - - } - -}); - -/** -* The world X coordinate of the most recently active pointer. -* @name Phaser.Input#worldX -* @property {number} worldX - The world X coordinate of the most recently active pointer. -*/ -Object.defineProperty(Phaser.Input.prototype, "worldX", { - - get: function () { - return this.game.camera.view.x + this.x; - } - -}); - -/** -* The world Y coordinate of the most recently active pointer. -* @name Phaser.Input#worldY -* @property {number} worldY - The world Y coordinate of the most recently active pointer. -*/ -Object.defineProperty(Phaser.Input.prototype, "worldY", { - - get: function () { - return this.game.camera.view.y + this.y; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* @class Phaser.Key -* @classdesc If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects. -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {number} keycode - The key code this Key is responsible for. -*/ -Phaser.Key = function (game, keycode) { - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {boolean} isDown - The "down" state of the key. - * @default - */ - this.isDown = false; - - /** - * @property {boolean} isUp - The "up" state of the key. - * @default - */ - this.isUp = false; - - /** - * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key. - * @default - */ - this.altKey = false; - - /** - * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key. - * @default - */ - this.ctrlKey = false; - - /** - * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key. - * @default - */ - this.shiftKey = false; - - /** - * @property {number} timeDown - The timestamp when the key was last pressed down. - * @default - */ - this.timeDown = 0; - - /** - * If the key is down this value holds the duration of that key press and is constantly updated. - * If the key is up it holds the duration of the previous down session. - * @property {number} duration - The number of milliseconds this key has been held down for. - * @default - */ - this.duration = 0; - - /** - * @property {number} timeUp - The timestamp when the key was last released. - * @default - */ - this.timeUp = 0; - - /** - * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'. - * @default - */ - this.repeats = 0; - - /** - * @property {number} keyCode - The keycode of this key. - */ - this.keyCode = keycode; - - /** - * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). - */ - this.onDown = new Phaser.Signal(); - - /** - * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again). - */ - this.onUp = new Phaser.Signal(); - -}; - -Phaser.Key.prototype = { - - /** - * Called automatically by Phaser.Keyboard. - * @method Phaser.Key#processKeyDown - * @param {KeyboardEvent} event. - * @protected - */ - processKeyDown: function (event) { - - this.altKey = event.altKey; - this.ctrlKey = event.ctrlKey; - this.shiftKey = event.shiftKey; - - if (this.isDown) - { - // Key was already held down, this must be a repeat rate based event - this.duration = event.timeStamp - this.timeDown; - this.repeats++; - } - else - { - this.isDown = true; - this.isUp = false; - this.timeDown = event.timeStamp; - this.duration = 0; - this.repeats = 0; - - this.onDown.dispatch(this); - } - - }, - - /** - * Called automatically by Phaser.Keyboard. - * @method Phaser.Key#processKeyUp - * @param {KeyboardEvent} event. - * @protected - */ - processKeyUp: function (event) { - - this.isDown = false; - this.isUp = true; - this.timeUp = event.timeStamp; - - this.onUp.dispatch(this); - - }, - - /** - * Returns the "just pressed" state of the Key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms) - * @method Phaser.Key#justPressed - * @param {number} [duration=250] - The duration below which the key is considered as being just pressed. - * @return {boolean} True if the key is just pressed otherwise false. - */ - justPressed: function (duration) { - - if (typeof duration === "undefined") { duration = 250; } - - return (this.isDown && this.duration < duration); - - }, - - /** - * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms) - * @method Phaser.Key#justPressed - * @param {number} [duration=250] - The duration below which the key is considered as being just released. - * @return {boolean} True if the key is just released otherwise false. - */ - justReleased: function (duration) { - - if (typeof duration === "undefined") { duration = 250; } - - return (this.isDown == false && (this.game.time.now - this.timeUp < duration)); - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser - Keyboard constructor. -* -* @class Phaser.Keyboard -* @classdesc A Keyboard object Description. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Keyboard = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Description} _keys - Description. - * @private - */ - this._keys = {}; - - /** - * @property {Description} _hotkeys - Description. - * @private - */ - this._hotkeys = {}; - - /** - * @property {Description} _capture - Description. - * @private - */ - this._capture = {}; - - /** - * You can disable all Keyboard Input by setting disabled to true. While true all new input related events will be ignored. - * @property {boolean} disabled - The disabled state of the Keyboard. - * @default - */ - this.disabled = false; - - /** - * @property {function} _onKeyDown - * @private - * @default - */ - this._onKeyDown = null; - - /** - * @property {function} _onKeyUp - * @private - * @default - */ - this._onKeyUp = null; - - /** - * @property {Object} callbackContext - The context under which the callbacks are run. - */ - this.callbackContext = this; - - /** - * @property {function} onDownCallback - This callback is invoked every time a key is pressed down. - */ - this.onDownCallback = null; - - /** - * @property {function} onUpCallback - This callback is invoked every time a key is released. - */ - this.onUpCallback = null; - -}; - -Phaser.Keyboard.prototype = { - - /** - * Add callbacks to the Keyboard handler so that each time a key is pressed down or releases the callbacks are activated. - * @method Phaser.Keyboard#addCallbacks - * @param {Object} context - The context under which the callbacks are run. - * @param {function} onDown - This callback is invoked every time a key is pressed down. - * @param {function} [onUp=null] - This callback is invoked every time a key is released. - */ - addCallbacks: function (context, onDown, onUp) { - - this.callbackContext = context; - this.onDownCallback = onDown; - - if (typeof onUp !== 'undefined') - { - this.onUpCallback = onUp; - } - - }, - - /** - * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method. - * The Key object can then be polled, have events attached to it, etc. - * - * @method Phaser.Keyboard#addKey - * @param {number} keycode - The keycode of the key, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR - * @return {Phaser.Key} The Key object which you can store locally and reference directly. - */ - addKey: function (keycode) { - - this._hotkeys[keycode] = new Phaser.Key(this.game, keycode); - - this.addKeyCapture(keycode); - - return this._hotkeys[keycode]; - - }, - - /** - * Removes a Key object from the Keyboard manager. - * - * @method Phaser.Keyboard#removeKey - * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR - */ - removeKey: function (keycode) { - - delete (this._hotkeys[keycode]); - - }, - - /** - * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right. - * - * @method Phaser.Keyboard#createCursorKeys - * @return {object} An object containing properties: up, down, left and right. Which can be polled like any other Phaser.Key object. - */ - createCursorKeys: function () { - - return { - up: this.addKey(Phaser.Keyboard.UP), - down: this.addKey(Phaser.Keyboard.DOWN), - left: this.addKey(Phaser.Keyboard.LEFT), - right: this.addKey(Phaser.Keyboard.RIGHT) - } - - }, - - /** - * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the document.body. - * This is called automatically by Phaser.Input and should not normally be invoked directly. - * - * @method Phaser.Keyboard#start - */ - start: function () { - - var _this = this; - - this._onKeyDown = function (event) { - return _this.processKeyDown(event); - }; - - this._onKeyUp = function (event) { - return _this.processKeyUp(event); - }; - - document.body.addEventListener('keydown', this._onKeyDown, false); - document.body.addEventListener('keyup', this._onKeyUp, false); - - }, - - /** - * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the document.body. - * - * @method Phaser.Keyboard#stop - */ - stop: function () { - - document.body.removeEventListener('keydown', this._onKeyDown); - document.body.removeEventListener('keyup', this._onKeyUp); - - }, - - /** - * By default when a key is pressed Phaser will not stop the event from propagating up to the browser. - * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll. - * You can use addKeyCapture to consume the keyboard event for specific keys so it doesn't bubble up to the the browser. - * Pass in either a single keycode or an array/hash of keycodes. - * @method Phaser.Keyboard#addKeyCapture - * @param {Any} keycode - */ - addKeyCapture: function (keycode) { - - if (typeof keycode === 'object') - { - for (var key in keycode) - { - this._capture[keycode[key]] = true; - } - } - else - { - this._capture[keycode] = true; - } - }, - - /** - * Removes an existing key capture. - * @method Phaser.Keyboard#removeKeyCapture - * @param {number} keycode - */ - removeKeyCapture: function (keycode) { - - delete this._capture[keycode]; - - }, - - /** - * Clear all set key captures. - * @method Phaser.Keyboard#clearCaptures - */ - clearCaptures: function () { - - this._capture = {}; - - }, - - /** - * Process the keydown event. - * @method Phaser.Keyboard#processKeyDown - * @param {KeyboardEvent} event - * @protected - */ - processKeyDown: function (event) { - - if (this.game.input.disabled || this.disabled) - { - return; - } - - if (this._capture[event.keyCode]) - { - event.preventDefault(); - } - - if (this.onDownCallback) - { - this.onDownCallback.call(this.callbackContext, event); - } - - if (this._keys[event.keyCode] && this._keys[event.keyCode].isDown) - { - // Key already down and still down, so update - this._keys[event.keyCode].duration = this.game.time.now - this._keys[event.keyCode].timeDown; - } - else - { - if (!this._keys[event.keyCode]) - { - // Not used this key before, so register it - this._keys[event.keyCode] = { - isDown: true, - timeDown: this.game.time.now, - timeUp: 0, - duration: 0 - }; - } - else - { - // Key used before but freshly down - this._keys[event.keyCode].isDown = true; - this._keys[event.keyCode].timeDown = this.game.time.now; - this._keys[event.keyCode].duration = 0; - } - } - - if (this._hotkeys[event.keyCode]) - { - this._hotkeys[event.keyCode].processKeyDown(event); - } - - }, - - /** - * Process the keyup event. - * @method Phaser.Keyboard#processKeyUp - * @param {KeyboardEvent} event - * @protected - */ - processKeyUp: function (event) { - - if (this.game.input.disabled || this.disabled) - { - return; - } - - if (this._capture[event.keyCode]) - { - event.preventDefault(); - } - - if (this.onUpCallback) - { - this.onUpCallback.call(this.callbackContext, event); - } - - if (this._hotkeys[event.keyCode]) - { - this._hotkeys[event.keyCode].processKeyUp(event); - } - - if (this._keys[event.keyCode]) - { - this._keys[event.keyCode].isDown = false; - this._keys[event.keyCode].timeUp = this.game.time.now; - } - else - { - // Not used this key before, so register it - this._keys[event.keyCode] = { - isDown: false, - timeDown: this.game.time.now, - timeUp: this.game.time.now, - duration: 0 - }; - } - - }, - - /** - * Reset the "isDown" state of all keys. - * @method Phaser.Keyboard#reset - */ - reset: function () { - - for (var key in this._keys) - { - this._keys[key].isDown = false; - } - - }, - - /** - * Returns the "just pressed" state of the key. Just pressed is considered true if the key was pressed down within the duration given (default 250ms) - * @method Phaser.Keyboard#justPressed - * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR - * @param {number} [duration=250] - The duration below which the key is considered as being just pressed. - * @return {boolean} True if the key is just pressed otherwise false. - */ - justPressed: function (keycode, duration) { - - if (typeof duration === "undefined") { duration = 250; } - - if (this._keys[keycode] && this._keys[keycode].isDown && this._keys[keycode].duration < duration) - { - return true; - } - - return false; - - }, - - /** - * Returns the "just released" state of the Key. Just released is considered as being true if the key was released within the duration given (default 250ms) - * @method Phaser.Keyboard#justPressed - * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR - * @param {number} [duration=250] - The duration below which the key is considered as being just released. - * @return {boolean} True if the key is just released otherwise false. - */ - justReleased: function (keycode, duration) { - - if (typeof duration === "undefined") { duration = 250; } - - if (this._keys[keycode] && this._keys[keycode].isDown === false && (this.game.time.now - this._keys[keycode].timeUp < duration)) - { - return true; - } - - return false; - - }, - - /** - * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser. - * @method Phaser.Keyboard#isDown - * @param {number} keycode - The keycode of the key to remove, i.e. Phaser.Keyboard.UP or Phaser.Keyboard.SPACE_BAR - * @return {boolean} True if the key is currently down. - */ - isDown: function (keycode) { - - if (this._keys[keycode]) - { - return this._keys[keycode].isDown; - } - - return false; - - } - -}; - -Phaser.Keyboard.A = "A".charCodeAt(0); -Phaser.Keyboard.B = "B".charCodeAt(0); -Phaser.Keyboard.C = "C".charCodeAt(0); -Phaser.Keyboard.D = "D".charCodeAt(0); -Phaser.Keyboard.E = "E".charCodeAt(0); -Phaser.Keyboard.F = "F".charCodeAt(0); -Phaser.Keyboard.G = "G".charCodeAt(0); -Phaser.Keyboard.H = "H".charCodeAt(0); -Phaser.Keyboard.I = "I".charCodeAt(0); -Phaser.Keyboard.J = "J".charCodeAt(0); -Phaser.Keyboard.K = "K".charCodeAt(0); -Phaser.Keyboard.L = "L".charCodeAt(0); -Phaser.Keyboard.M = "M".charCodeAt(0); -Phaser.Keyboard.N = "N".charCodeAt(0); -Phaser.Keyboard.O = "O".charCodeAt(0); -Phaser.Keyboard.P = "P".charCodeAt(0); -Phaser.Keyboard.Q = "Q".charCodeAt(0); -Phaser.Keyboard.R = "R".charCodeAt(0); -Phaser.Keyboard.S = "S".charCodeAt(0); -Phaser.Keyboard.T = "T".charCodeAt(0); -Phaser.Keyboard.U = "U".charCodeAt(0); -Phaser.Keyboard.V = "V".charCodeAt(0); -Phaser.Keyboard.W = "W".charCodeAt(0); -Phaser.Keyboard.X = "X".charCodeAt(0); -Phaser.Keyboard.Y = "Y".charCodeAt(0); -Phaser.Keyboard.Z = "Z".charCodeAt(0); -Phaser.Keyboard.ZERO = "0".charCodeAt(0); -Phaser.Keyboard.ONE = "1".charCodeAt(0); -Phaser.Keyboard.TWO = "2".charCodeAt(0); -Phaser.Keyboard.THREE = "3".charCodeAt(0); -Phaser.Keyboard.FOUR = "4".charCodeAt(0); -Phaser.Keyboard.FIVE = "5".charCodeAt(0); -Phaser.Keyboard.SIX = "6".charCodeAt(0); -Phaser.Keyboard.SEVEN = "7".charCodeAt(0); -Phaser.Keyboard.EIGHT = "8".charCodeAt(0); -Phaser.Keyboard.NINE = "9".charCodeAt(0); -Phaser.Keyboard.NUMPAD_0 = 96; -Phaser.Keyboard.NUMPAD_1 = 97; -Phaser.Keyboard.NUMPAD_2 = 98; -Phaser.Keyboard.NUMPAD_3 = 99; -Phaser.Keyboard.NUMPAD_4 = 100; -Phaser.Keyboard.NUMPAD_5 = 101; -Phaser.Keyboard.NUMPAD_6 = 102; -Phaser.Keyboard.NUMPAD_7 = 103; -Phaser.Keyboard.NUMPAD_8 = 104; -Phaser.Keyboard.NUMPAD_9 = 105; -Phaser.Keyboard.NUMPAD_MULTIPLY = 106; -Phaser.Keyboard.NUMPAD_ADD = 107; -Phaser.Keyboard.NUMPAD_ENTER = 108; -Phaser.Keyboard.NUMPAD_SUBTRACT = 109; -Phaser.Keyboard.NUMPAD_DECIMAL = 110; -Phaser.Keyboard.NUMPAD_DIVIDE = 111; -Phaser.Keyboard.F1 = 112; -Phaser.Keyboard.F2 = 113; -Phaser.Keyboard.F3 = 114; -Phaser.Keyboard.F4 = 115; -Phaser.Keyboard.F5 = 116; -Phaser.Keyboard.F6 = 117; -Phaser.Keyboard.F7 = 118; -Phaser.Keyboard.F8 = 119; -Phaser.Keyboard.F9 = 120; -Phaser.Keyboard.F10 = 121; -Phaser.Keyboard.F11 = 122; -Phaser.Keyboard.F12 = 123; -Phaser.Keyboard.F13 = 124; -Phaser.Keyboard.F14 = 125; -Phaser.Keyboard.F15 = 126; -Phaser.Keyboard.COLON = 186; -Phaser.Keyboard.EQUALS = 187; -Phaser.Keyboard.UNDERSCORE = 189; -Phaser.Keyboard.QUESTION_MARK = 191; -Phaser.Keyboard.TILDE = 192; -Phaser.Keyboard.OPEN_BRACKET = 219; -Phaser.Keyboard.BACKWARD_SLASH = 220; -Phaser.Keyboard.CLOSED_BRACKET = 221; -Phaser.Keyboard.QUOTES = 222; -Phaser.Keyboard.BACKSPACE = 8; -Phaser.Keyboard.TAB = 9; -Phaser.Keyboard.CLEAR = 12; -Phaser.Keyboard.ENTER = 13; -Phaser.Keyboard.SHIFT = 16; -Phaser.Keyboard.CONTROL = 17; -Phaser.Keyboard.ALT = 18; -Phaser.Keyboard.CAPS_LOCK = 20; -Phaser.Keyboard.ESC = 27; -Phaser.Keyboard.SPACEBAR = 32; -Phaser.Keyboard.PAGE_UP = 33; -Phaser.Keyboard.PAGE_DOWN = 34; -Phaser.Keyboard.END = 35; -Phaser.Keyboard.HOME = 36; -Phaser.Keyboard.LEFT = 37; -Phaser.Keyboard.UP = 38; -Phaser.Keyboard.RIGHT = 39; -Phaser.Keyboard.DOWN = 40; -Phaser.Keyboard.INSERT = 45; -Phaser.Keyboard.DELETE = 46; -Phaser.Keyboard.HELP = 47; -Phaser.Keyboard.NUM_LOCK = 144; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser - Mouse constructor. -* -* @class Phaser.Mouse -* @classdesc The Mouse class -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Mouse = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Object} callbackContext - Description. - */ - this.callbackContext = this.game; - - /** - * @property {function} mouseDownCallback - Description. - * @default - */ - this.mouseDownCallback = null; - - /** - * @property {function} mouseMoveCallback - Description. - * @default - */ - this.mouseMoveCallback = null; - - /** - * @property {function} mouseUpCallback - Description. - * @default - */ - this.mouseUpCallback = null; - - /** - * @property {number} button- The type of click, either: Phaser.Mouse.NO_BUTTON, Phaser.Mouse.LEFT_BUTTON, Phaser.Mouse.MIDDLE_BUTTON or Phaser.Mouse.RIGHT_BUTTON. - * @default - */ - this.button = -1; - - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @property {boolean} disabled - * @default - */ - this.disabled = false; - - /** - * If the mouse has been Pointer Locked successfully this will be set to true. - * @property {boolean} locked - * @default - */ - this.locked = false; - - /** - * This event is dispatched when the browser enters or leaves pointer lock state. - * @property {Phaser.Signal} pointerLock - * @default - */ - this.pointerLock = new Phaser.Signal; - - /** - * The browser mouse event. - * @property {MouseEvent} event - */ - this.event; - - /** - * @property {function} _onMouseDown - * @private - */ - this._onMouseDown; - - /** - * @property {function} _onMouseMove - * @private - */ - this._onMouseMove; - - /** - * @property {function} _onMouseUp - * @private - */ - this._onMouseUp; - -}; - -/** -* @constant -* @type {number} -*/ -Phaser.Mouse.NO_BUTTON = -1; -/** -* @constant -* @type {number} -*/ -Phaser.Mouse.LEFT_BUTTON = 0; - -/** -* @constant -* @type {number} -*/ -Phaser.Mouse.MIDDLE_BUTTON = 1; - -/** -* @constant -* @type {number} -*/ -Phaser.Mouse.RIGHT_BUTTON = 2; - -Phaser.Mouse.prototype = { - - /** - * Starts the event listeners running. - * @method Phaser.Mouse#start - */ - start: function () { - - var _this = this; - - if (this.game.device.android && this.game.device.chrome == false) - { - // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ... - return; - } - - this._onMouseDown = function (event) { - return _this.onMouseDown(event); - }; - - this._onMouseMove = function (event) { - return _this.onMouseMove(event); - }; - - this._onMouseUp = function (event) { - return _this.onMouseUp(event); - }; - - // this.game.renderer.view.addEventListener('mousedown', this._onMouseDown, true); - // this.game.renderer.view.addEventListener('mousemove', this._onMouseMove, true); - // this.game.renderer.view.addEventListener('mouseup', this._onMouseUp, true); - - document.addEventListener('mousedown', this._onMouseDown, true); - document.addEventListener('mousemove', this._onMouseMove, true); - document.addEventListener('mouseup', this._onMouseUp, true); - - }, - - /** - * The internal method that handles the mouse down event from the browser. - * @method Phaser.Mouse#onMouseDown - * @param {MouseEvent} event - */ - onMouseDown: function (event) { - - this.event = event; - - event.preventDefault(); - - this.button = event.which; - - if (this.mouseDownCallback) - { - this.mouseDownCallback.call(this.callbackContext, event); - } - - if (this.game.input.disabled || this.disabled) - { - return; - } - - event['identifier'] = 0; - - this.game.input.mousePointer.start(event); - - }, - - /** - * The internal method that handles the mouse move event from the browser. - * @method Phaser.Mouse#onMouseMove - * @param {MouseEvent} event - */ - onMouseMove: function (event) { - - this.event = event; - - event.preventDefault(); - - if (this.mouseMoveCallback) - { - this.mouseMoveCallback.call(this.callbackContext, event); - } - - if (this.game.input.disabled || this.disabled) - { - return; - } - - event['identifier'] = 0; - - this.game.input.mousePointer.move(event); - - }, - - /** - * The internal method that handles the mouse up event from the browser. - * @method Phaser.Mouse#onMouseUp - * @param {MouseEvent} event - */ - onMouseUp: function (event) { - - this.event = event; - - event.preventDefault(); - - this.button = Phaser.Mouse.NO_BUTTON; - - if (this.mouseUpCallback) - { - this.mouseUpCallback.call(this.callbackContext, event); - } - - if (this.game.input.disabled || this.disabled) - { - return; - } - - event['identifier'] = 0; - - this.game.input.mousePointer.stop(event); - - }, - - /** - * If the browser supports it you can request that the pointer be locked to the browser window. - * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key. - * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'. - * @method Phaser.Mouse#requestPointerLock - */ - requestPointerLock: function () { - - if (this.game.device.pointerLock) - { - var element = this.game.stage.canvas; - - element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock; - - element.requestPointerLock(); - - var _this = this; - - this._pointerLockChange = function (event) { - return _this.pointerLockChange(event); - }; - - document.addEventListener('pointerlockchange', this._pointerLockChange, true); - document.addEventListener('mozpointerlockchange', this._pointerLockChange, true); - document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true); - } - - }, - - /** - * Internal pointerLockChange handler. - * @method Phaser.Mouse#pointerLockChange - * @param {MouseEvent} event - */ - pointerLockChange: function (event) { - - var element = this.game.stage.canvas; - - if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) - { - // Pointer was successfully locked - this.locked = true; - this.pointerLock.dispatch(true); - } - else - { - // Pointer was unlocked - this.locked = false; - this.pointerLock.dispatch(false); - } - - }, - - /** - * Internal release pointer lock handler. - * @method Phaser.Mouse#releasePointerLock - */ - releasePointerLock: function () { - - document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock; - - document.exitPointerLock(); - - document.removeEventListener('pointerlockchange', this._pointerLockChange, true); - document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true); - document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true); - - }, - - /** - * Stop the event listeners. - * @method Phaser.Mouse#stop - */ - stop: function () { - - // this.game.stage.canvas.removeEventListener('mousedown', this._onMouseDown, true); - // this.game.stage.canvas.removeEventListener('mousemove', this._onMouseMove, true); - // this.game.stage.canvas.removeEventListener('mouseup', this._onMouseUp, true); - - document.removeEventListener('mousedown', this._onMouseDown, true); - document.removeEventListener('mousemove', this._onMouseMove, true); - document.removeEventListener('mouseup', this._onMouseUp, true); - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser - MSPointer constructor. -* -* @class Phaser.MSPointer -* @classdesc The MSPointer class handles touch interactions with the game and the resulting Pointer objects. -* It will work only in Internet Explorer 10 and Windows Store or Windows Phone 8 apps using JavaScript. -* http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.MSPointer = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Phaser.Game} callbackContext - Description. - */ - this.callbackContext = this.game; - - /** - * @property {Description} mouseDownCallback - Description. - * @default - */ - this.mouseDownCallback = null; - - /** - * @property {Description} mouseMoveCallback - Description. - * @default - */ - this.mouseMoveCallback = null; - - /** - * @property {Description} mouseUpCallback - Description. - * @default - */ - this.mouseUpCallback = null; - - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @property {boolean} disabled - */ - this.disabled = false; - - /** - * Description. - * @property {Description} _onMSPointerDown - * @private - * @default - */ - this._onMSPointerDown = null; - - /** - * Description. - * @property {Description} _onMSPointerMove - * @private - * @default - */ - this._onMSPointerMove = null; - - /** - * Description. - * @property {Description} _onMSPointerUp - * @private - * @default - */ - this._onMSPointerUp = null; - -}; - -Phaser.MSPointer.prototype = { - - /** - * Starts the event listeners running. - * @method Phaser.MSPointer#start - */ - start: function () { - - var _this = this; - - if (this.game.device.mspointer == true) - { - this._onMSPointerDown = function (event) { - return _this.onPointerDown(event); - }; - - this._onMSPointerMove = function (event) { - return _this.onPointerMove(event); - }; - - this._onMSPointerUp = function (event) { - return _this.onPointerUp(event); - }; - - this.game.renderer.view.addEventListener('MSPointerDown', this._onMSPointerDown, false); - this.game.renderer.view.addEventListener('MSPointerMove', this._onMSPointerMove, false); - this.game.renderer.view.addEventListener('MSPointerUp', this._onMSPointerUp, false); - - this.game.renderer.view.style['-ms-content-zooming'] = 'none'; - this.game.renderer.view.style['-ms-touch-action'] = 'none'; - - } - - }, - - /** - * Description. - * @method Phaser.MSPointer#onPointerDown - * @param {Any} event - **/ - onPointerDown: function (event) { - - if (this.game.input.disabled || this.disabled) - { - return; - } - - event.preventDefault(); - event.identifier = event.pointerId; - - this.game.input.startPointer(event); - - }, - - /** - * Description. - * @method Phaser.MSPointer#onPointerMove - * @param {Any} event - **/ - onPointerMove: function (event) { - - if (this.game.input.disabled || this.disabled) - { - return; - } - - event.preventDefault(); - event.identifier = event.pointerId; - - this.game.input.updatePointer(event); - - }, - - /** - * Description. - * @method Phaser.MSPointer#onPointerUp - * @param {Any} event - **/ - onPointerUp: function (event) { - - if (this.game.input.disabled || this.disabled) - { - return; - } - - event.preventDefault(); - event.identifier = event.pointerId; - - this.game.input.stopPointer(event); - - }, - - /** - * Stop the event listeners. - * @method Phaser.MSPointer#stop - */ - stop: function () { - - this.game.stage.canvas.removeEventListener('MSPointerDown', this._onMSPointerDown); - this.game.stage.canvas.removeEventListener('MSPointerMove', this._onMSPointerMove); - this.game.stage.canvas.removeEventListener('MSPointerUp', this._onMSPointerUp); - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser - Pointer constructor. -* -* @class Phaser.Pointer -* @classdesc A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Description} id - Description. -*/ -Phaser.Pointer = function (game, id) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Description} id - Description. - */ - this.id = id; - - /** - * Local private variable to store the status of dispatching a hold event. - * @property {boolean} _holdSent - * @private - * @default - */ - this._holdSent = false; - - /** - * Local private variable storing the short-term history of pointer movements. - * @property {array} _history - * @private - */ - this._history = []; - - /** - * Local private variable storing the time at which the next history drop should occur - * @property {number} _lastDrop - * @private - * @default - */ - this._nextDrop = 0; - - /** - * Monitor events outside of a state reset loop. - * @property {boolean} _stateReset - * @private - * @default - */ - this._stateReset = false; - - /** - * Description. - * @property {boolean} withinGame - */ - this.withinGame = false; - - /** - * The horizontal coordinate of point relative to the viewport in pixels, excluding any scroll offset. - * @property {number} clientX - * @default - */ - this.clientX = -1; - - /** - * The vertical coordinate of point relative to the viewport in pixels, excluding any scroll offset. - * @property {number} clientY - * @default - */ - this.clientY = -1; - - /** - * The horizontal coordinate of point relative to the viewport in pixels, including any scroll offset. - * @property {number} pageX - * @default - */ - this.pageX = -1; - - /** - * The vertical coordinate of point relative to the viewport in pixels, including any scroll offset. - * @property {number} pageY - * @default - */ - this.pageY = -1; - - /** - * The horizontal coordinate of point relative to the screen in pixels. - * @property {number} screenX - * @default - */ - this.screenX = -1; - - /** - * The vertical coordinate of point relative to the screen in pixels. - * @property {number} screenY - * @default - */ - this.screenY = -1; - - /** - * The horizontal coordinate of point relative to the game element. This value is automatically scaled based on game size. - * @property {number} x - * @default - */ - this.x = -1; - - /** - * The vertical coordinate of point relative to the game element. This value is automatically scaled based on game size. - * @property {number} y - * @default - */ - this.y = -1; - - /** - * If the Pointer is a mouse this is true, otherwise false. - * @property {boolean} isMouse - * @type {boolean} - */ - this.isMouse = false; - - /** - * If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true. - * @property {boolean} isDown - * @default - */ - this.isDown = false; - - /** - * If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true. - * @property {boolean} isUp - * @default - */ - this.isUp = true; - - /** - * A timestamp representing when the Pointer first touched the touchscreen. - * @property {number} timeDown - * @default - */ - this.timeDown = 0; - - /** - * A timestamp representing when the Pointer left the touchscreen. - * @property {number} timeUp - * @default - */ - this.timeUp = 0; - - /** - * A timestamp representing when the Pointer was last tapped or clicked. - * @property {number} previousTapTime - * @default - */ - this.previousTapTime = 0; - - /** - * The total number of times this Pointer has been touched to the touchscreen. - * @property {number} totalTouches - * @default - */ - this.totalTouches = 0; - - /** - * The number of miliseconds since the last click. - * @property {number} msSinceLastClick - * @default - */ - this.msSinceLastClick = Number.MAX_VALUE; - - /** - * The Game Object this Pointer is currently over / touching / dragging. - * @property {Any} targetObject - * @default - */ - this.targetObject = null; - - /** - * An active pointer is one that is currently pressed down on the display. A Mouse is always active. - * @property {boolean} active - * @default - */ - this.active = false; - - /** - * A Phaser.Point object containing the current x/y values of the pointer on the display. - * @property {Phaser.Point} position - */ - this.position = new Phaser.Point(); - - /** - * A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display. - * @property {Phaser.Point} positionDown - */ - this.positionDown = new Phaser.Point(); - - /** - * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection. - * The Circle size is 44px (Apples recommended "finger tip" size). - * @property {Phaser.Circle} circle - */ - this.circle = new Phaser.Circle(0, 0, 44); - - if (id == 0) - { - this.isMouse = true; - } - -}; - -Phaser.Pointer.prototype = { - - /** - * Called when the Pointer is pressed onto the touchscreen. - * @method Phaser.Pointer#start - * @param {Any} event - */ - start: function (event) { - - this.identifier = event.identifier; - this.target = event.target; - - if (typeof event.button !== 'undefined') - { - this.button = event.button; - } - - // Fix to stop rogue browser plugins from blocking the visibility state event - if (this.game.paused == true && this.game.stage.scale.incorrectOrientation == false) - { - this.game.paused = false; - return this; - } - - this._history.length = 0; - this.active = true; - this.withinGame = true; - this.isDown = true; - this.isUp = false; - - // Work out how long it has been since the last click - this.msSinceLastClick = this.game.time.now - this.timeDown; - this.timeDown = this.game.time.now; - this._holdSent = false; - - // This sets the x/y and other local values - this.move(event); - - // x and y are the old values here? - this.positionDown.setTo(this.x, this.y); - - if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers == 0)) - { - this.game.input.x = this.x; - this.game.input.y = this.y; - this.game.input.position.setTo(this.x, this.y); - this.game.input.onDown.dispatch(this, event); - this.game.input.resetSpeed(this.x, this.y); - } - - this._stateReset = false; - this.totalTouches++; - - if (this.isMouse == false) - { - this.game.input.currentPointers++; - } - - if (this.targetObject !== null) - { - this.targetObject._touchedHandler(this); - } - - return this; - - }, - - /** - * Description. - * @method Phaser.Pointer#update - */ - update: function () { - - if (this.active) - { - if (this._holdSent == false && this.duration >= this.game.input.holdRate) - { - if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers == 0)) - { - this.game.input.onHold.dispatch(this); - } - - this._holdSent = true; - } - - // Update the droppings history - if (this.game.input.recordPointerHistory && this.game.time.now >= this._nextDrop) - { - this._nextDrop = this.game.time.now + this.game.input.recordRate; - - this._history.push({ - x: this.position.x, - y: this.position.y - }); - - if (this._history.length > this.game.input.recordLimit) - { - this._history.shift(); - } - } - } - - }, - - /** - * Called when the Pointer is moved - * @method Phaser.Pointer#move - * @param {Any} event - */ - move: function (event) { - - if (this.game.input.pollLocked) - { - return; - } - - if (typeof event.button !== 'undefined') - { - this.button = event.button; - } - - this.clientX = event.clientX; - this.clientY = event.clientY; - - this.pageX = event.pageX; - this.pageY = event.pageY; - - this.screenX = event.screenX; - this.screenY = event.screenY; - - this.x = (this.pageX - this.game.stage.offset.x) * this.game.input.scale.x; - this.y = (this.pageY - this.game.stage.offset.y) * this.game.input.scale.y; - - this.position.setTo(this.x, this.y); - this.circle.x = this.x; - this.circle.y = this.y; - - if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers == 0)) - { - this.game.input.activePointer = this; - this.game.input.x = this.x; - this.game.input.y = this.y; - this.game.input.position.setTo(this.game.input.x, this.game.input.y); - this.game.input.circle.x = this.game.input.x; - this.game.input.circle.y = this.game.input.y; - } - - // If the game is paused we don't process any target objects - if (this.game.paused) - { - return this; - } - - // Easy out if we're dragging something and it still exists - if (this.targetObject !== null && this.targetObject.isDragged == true) - { - if (this.targetObject.update(this) == false) - { - this.targetObject = null; - } - - return this; - } - - // Work out which object is on the top - this._highestRenderOrderID = -1; - this._highestRenderObject = null; - this._highestInputPriorityID = -1; - - // Just run through the linked list - if (this.game.input.interactiveItems.total > 0) - { - var currentNode = this.game.input.interactiveItems.next; - - do - { - // If the object is using pixelPerfect checks, or has a higher InputManager.PriorityID OR if the priority ID is the same as the current highest AND it has a higher renderOrderID, then set it to the top - if (currentNode.pixelPerfect || currentNode.priorityID > this._highestInputPriorityID || (currentNode.priorityID == this._highestInputPriorityID && currentNode.sprite.renderOrderID > this._highestRenderOrderID)) - { - if (currentNode.checkPointerOver(this)) - { - // console.log('HRO set', currentNode.sprite.name); - this._highestRenderOrderID = currentNode.sprite.renderOrderID; - this._highestInputPriorityID = currentNode.priorityID; - this._highestRenderObject = currentNode; - } - } - currentNode = currentNode.next; - } - while (currentNode != null) - } - - if (this._highestRenderObject == null) - { - // The pointer isn't currently over anything, check if we've got a lingering previous target - if (this.targetObject) - { - // console.log("The pointer isn't currently over anything, check if we've got a lingering previous target"); - this.targetObject._pointerOutHandler(this); - this.targetObject = null; - } - } - else - { - if (this.targetObject == null) - { - // And now set the new one - // console.log('And now set the new one'); - this.targetObject = this._highestRenderObject; - this._highestRenderObject._pointerOverHandler(this); - } - else - { - // We've got a target from the last update - // console.log("We've got a target from the last update"); - if (this.targetObject == this._highestRenderObject) - { - // Same target as before, so update it - // console.log("Same target as before, so update it"); - if (this._highestRenderObject.update(this) == false) - { - this.targetObject = null; - } - } - else - { - // The target has changed, so tell the old one we've left it - // console.log("The target has changed, so tell the old one we've left it"); - this.targetObject._pointerOutHandler(this); - - // And now set the new one - this.targetObject = this._highestRenderObject; - this.targetObject._pointerOverHandler(this); - } - } - } - - return this; - - }, - - /** - * Called when the Pointer leaves the target area. - * @method Phaser.Pointer#leave - * @param {Any} event - */ - leave: function (event) { - - this.withinGame = false; - this.move(event); - - }, - - /** - * Called when the Pointer leaves the touchscreen. - * @method Phaser.Pointer#stop - * @param {Any} event - */ - stop: function (event) { - - if (this._stateReset) - { - event.preventDefault(); - return; - } - - this.timeUp = this.game.time.now; - - if (this.game.input.multiInputOverride == Phaser.Input.MOUSE_OVERRIDES_TOUCH || this.game.input.multiInputOverride == Phaser.Input.MOUSE_TOUCH_COMBINE || (this.game.input.multiInputOverride == Phaser.Input.TOUCH_OVERRIDES_MOUSE && this.game.input.currentPointers == 0)) - { - this.game.input.onUp.dispatch(this, event); - - // Was it a tap? - if (this.duration >= 0 && this.duration <= this.game.input.tapRate) - { - // Was it a double-tap? - if (this.timeUp - this.previousTapTime < this.game.input.doubleTapRate) - { - // Yes, let's dispatch the signal then with the 2nd parameter set to true - this.game.input.onTap.dispatch(this, true); - } - else - { - // Wasn't a double-tap, so dispatch a single tap signal - this.game.input.onTap.dispatch(this, false); - } - - this.previousTapTime = this.timeUp; - } - } - - // Mouse is always active - if (this.id > 0) - { - this.active = false; - } - - this.withinGame = false; - this.isDown = false; - this.isUp = true; - - if (this.isMouse == false) - { - this.game.input.currentPointers--; - } - - if (this.game.input.interactiveItems.total > 0) - { - var currentNode = this.game.input.interactiveItems.next; - - do - { - if (currentNode) - { - currentNode._releasedHandler(this); - } - - currentNode = currentNode.next; - } - while (currentNode != null) - } - - if (this.targetObject) - { - this.targetObject._releasedHandler(this); - } - - this.targetObject = null; - return this; - - }, - - /** - * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate. - * @method Phaser.Pointer#justPressed - * @param {number} [duration] - * @return {boolean} - */ - justPressed: function (duration) { - - duration = duration || this.game.input.justPressedRate; - - return (this.isDown === true && (this.timeDown + duration) > this.game.time.now); - - }, - - /** - * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate. - * @method Phaser.Pointer#justReleased - * @param {number} [duration] - * @return {boolean} - */ - justReleased: function (duration) { - - duration = duration || this.game.input.justReleasedRate; - - return (this.isUp === true && (this.timeUp + duration) > this.game.time.now); - - }, - - /** - * Resets the Pointer properties. Called by InputManager.reset when you perform a State change. - * @method Phaser.Pointer#reset - */ - reset: function () { - - if (this.isMouse == false) - { - this.active = false; - } - - this.identifier = null; - this.isDown = false; - this.isUp = true; - this.totalTouches = 0; - this._holdSent = false; - this._history.length = 0; - this._stateReset = true; - - if (this.targetObject) - { - this.targetObject._releasedHandler(this); - } - - this.targetObject = null; - - }, - - /** - * Returns a string representation of this object. - * @method Phaser.Pointer#toString - * @return {string} A string representation of the instance. - **/ - toString: function () { - return "[{Pointer (id=" + this.id + " identifer=" + this.identifier + " active=" + this.active + " duration=" + this.duration + " withinGame=" + this.withinGame + " x=" + this.x + " y=" + this.y + " clientX=" + this.clientX + " clientY=" + this.clientY + " screenX=" + this.screenX + " screenY=" + this.screenY + " pageX=" + this.pageX + " pageY=" + this.pageY + ")}]"; - } - -}; - -/** -* How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1. -* @name Phaser.Pointer#duration -* @property {number} duration - How long the Pointer has been depressed on the touchscreen. If not currently down it returns -1. -* @readonly -*/ -Object.defineProperty(Phaser.Pointer.prototype, "duration", { - - get: function () { - - if (this.isUp) - { - return -1; - } - - return this.game.time.now - this.timeDown; - - } - -}); - -/** -* Gets the X value of this Pointer in world coordinates based on the world camera. -* @name Phaser.Pointer#worldX -* @property {number} duration - The X value of this Pointer in world coordinates based on the world camera. -* @readonly -*/ -Object.defineProperty(Phaser.Pointer.prototype, "worldX", { - - get: function () { - - return this.game.world.camera.x + this.x; - - } - -}); - -/** -* Gets the Y value of this Pointer in world coordinates based on the world camera. -* @name Phaser.Pointer#worldY -* @property {number} duration - The Y value of this Pointer in world coordinates based on the world camera. -* @readonly -*/ -Object.defineProperty(Phaser.Pointer.prototype, "worldY", { - - get: function () { - - return this.game.world.camera.y + this.y; - - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch. -* -* @class Phaser.Touch -* @classdesc The Touch class handles touch interactions with the game and the resulting Pointer objects. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Touch = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * You can disable all Input by setting disabled = true. While set all new input related events will be ignored. - * @method Phaser.Touch#disabled - * @return {boolean} - */ - this.disabled = false; - - /** - * @property {Phaser.Game} callbackContext - Description. - */ - this.callbackContext = this.game; - - /** - * @property {Phaser.Game} touchStartCallback - Description. - * @default - */ - this.touchStartCallback = null; - - /** - * @property {Phaser.Game} touchMoveCallback - Description. - * @default - */ - this.touchMoveCallback = null; - - /** - * @property {Phaser.Game} touchEndCallback - Description. - * @default - */ - this.touchEndCallback = null; - - /** - * @property {Phaser.Game} touchEnterCallback - Description. - * @default - */ - this.touchEnterCallback = null; - - /** - * @property {Phaser.Game} touchLeaveCallback - Description. - * @default - */ - this.touchLeaveCallback = null; - - /** - * @property {Description} touchCancelCallback - Description. - * @default - */ - this.touchCancelCallback = null; - - /** - * @property {boolean} preventDefault - Description. - * @default - */ - this.preventDefault = true; - - this._onTouchStart = null; - this._onTouchMove = null; - this._onTouchEnd = null; - this._onTouchEnter = null; - this._onTouchLeave = null; - this._onTouchCancel = null; - this._onTouchMove = null; - -}; - -Phaser.Touch.prototype = { - - /** - * Starts the event listeners running. - * @method Phaser.Touch#start - */ - start: function () { - - var _this = this; - - if (this.game.device.touch) - { - this._onTouchStart = function (event) { - return _this.onTouchStart(event); - }; - - this._onTouchMove = function (event) { - return _this.onTouchMove(event); - }; - - this._onTouchEnd = function (event) { - return _this.onTouchEnd(event); - }; - - this._onTouchEnter = function (event) { - return _this.onTouchEnter(event); - }; - - this._onTouchLeave = function (event) { - return _this.onTouchLeave(event); - }; - - this._onTouchCancel = function (event) { - return _this.onTouchCancel(event); - }; - - this.game.renderer.view.addEventListener('touchstart', this._onTouchStart, false); - this.game.renderer.view.addEventListener('touchmove', this._onTouchMove, false); - this.game.renderer.view.addEventListener('touchend', this._onTouchEnd, false); - this.game.renderer.view.addEventListener('touchenter', this._onTouchEnter, false); - this.game.renderer.view.addEventListener('touchleave', this._onTouchLeave, false); - this.game.renderer.view.addEventListener('touchcancel', this._onTouchCancel, false); - } - - }, - - /** - * Consumes all touchmove events on the document (only enable this if you know you need it!). - * @method Phaser.Touch#consumeTouchMove - */ - consumeDocumentTouches: function () { - - this._documentTouchMove = function (event) { - event.preventDefault(); - }; - - document.addEventListener('touchmove', this._documentTouchMove, false); - - }, - - /** - * Description. - * @method Phaser.Touch#onTouchStart - * @param {Any} event - */ - onTouchStart: function (event) { - - if (this.touchStartCallback) - { - this.touchStartCallback.call(this.callbackContext, event); - } - - if (this.game.input.disabled || this.disabled) - { - return; - } - - if (this.preventDefault) - { - event.preventDefault(); - } - - // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element) - // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - for (var i = 0; i < event.changedTouches.length; i++) - { - this.game.input.startPointer(event.changedTouches[i]); - } - - }, - - /** - * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome). - * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears. - * @method Phaser.Touch#onTouchCancel - * @param {Any} event - */ - onTouchCancel: function (event) { - - if (this.touchCancelCallback) - { - this.touchCancelCallback.call(this.callbackContext, event); - } - - if (this.game.input.disabled || this.disabled) - { - return; - } - - if (this.preventDefault) - { - event.preventDefault(); - } - - // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome) - // http://www.w3.org/TR/touch-events/#dfn-touchcancel - for (var i = 0; i < event.changedTouches.length; i++) - { - this.game.input.stopPointer(event.changedTouches[i]); - } - - }, - - /** - * For touch enter and leave its a list of the touch points that have entered or left the target. - * Doesn't appear to be supported by most browsers on a canvas element yet. - * @method Phaser.Touch#onTouchEnter - * @param {Any} event - */ - onTouchEnter: function (event) { - - if (this.touchEnterCallback) - { - this.touchEnterCallback.call(this.callbackContext, event); - } - - if (this.game.input.disabled || this.disabled) - { - return; - } - - if (this.preventDefault) - { - event.preventDefault(); - } - - for (var i = 0; i < event.changedTouches.length; i++) - { - //console.log('touch enter'); - } - - }, - - /** - * For touch enter and leave its a list of the touch points that have entered or left the target. - * Doesn't appear to be supported by most browsers on a canvas element yet. - * @method Phaser.Touch#onTouchLeave - * @param {Any} event - */ - onTouchLeave: function (event) { - - if (this.touchLeaveCallback) - { - this.touchLeaveCallback.call(this.callbackContext, event); - } - - if (this.preventDefault) - { - event.preventDefault(); - } - - for (var i = 0; i < event.changedTouches.length; i++) - { - //console.log('touch leave'); - } - - }, - - /** - * Description. - * @method Phaser.Touch#onTouchMove - * @param {Any} event - */ - onTouchMove: function (event) { - - if (this.touchMoveCallback) - { - this.touchMoveCallback.call(this.callbackContext, event); - } - - if (this.preventDefault) - { - event.preventDefault(); - } - - for (var i = 0; i < event.changedTouches.length; i++) - { - this.game.input.updatePointer(event.changedTouches[i]); - } - - }, - - /** - * Description. - * @method Phaser.Touch#onTouchEnd - * @param {Any} event - */ - onTouchEnd: function (event) { - - if (this.touchEndCallback) - { - this.touchEndCallback.call(this.callbackContext, event); - } - - if (this.preventDefault) - { - event.preventDefault(); - } - - // For touch end its a list of the touch points that have been removed from the surface - // https://developer.mozilla.org/en-US/docs/DOM/TouchList - // event.changedTouches = the touches that CHANGED in this event, not the total number of them - for (var i = 0; i < event.changedTouches.length; i++) - { - this.game.input.stopPointer(event.changedTouches[i]); - } - - }, - - /** - * Stop the event listeners. - * @method Phaser.Touch#stop - */ - stop: function () { - - if (this.game.device.touch) - { - this.game.stage.canvas.removeEventListener('touchstart', this._onTouchStart); - this.game.stage.canvas.removeEventListener('touchmove', this._onTouchMove); - this.game.stage.canvas.removeEventListener('touchend', this._onTouchEnd); - this.game.stage.canvas.removeEventListener('touchenter', this._onTouchEnter); - this.game.stage.canvas.removeEventListener('touchleave', this._onTouchLeave); - this.game.stage.canvas.removeEventListener('touchcancel', this._onTouchCancel); - } - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Constructor for Phaser InputHandler. -* @class Phaser.InputHandler -* @classdesc Description. -* @constructor -* @param {Phaser.Sprite} game - Description. -*/ -Phaser.InputHandler = function (sprite) { - - /** - * @property {Phaser.Sprite} sprite - Description. - */ - this.sprite = sprite; - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = sprite.game; - - /** - * @property {boolean} enabled - Description. - * @default - */ - this.enabled = false; - - // Linked list references - /** - * @property {Description} parent - Description. - * @default - */ - this.parent = null; - - /** - * @property {Description} next - Description. - * @default - */ - this.next = null; - - /** - * @property {Description} prev - Description. - * @default - */ - this.prev = null; - - /** - * @property {Description} last - Description. - * @default - */ - this.last = this; - - /** - * @property {Description} first - Description. - * @default - */ - this.first = this; - - /** - * @property {number} priorityID - The PriorityID controls which Sprite receives an Input event first if they should overlap. - * @default - */ - this.priorityID = 0; - - /** - * @property {boolean} useHandCursor - Description. - * @default - */ - this.useHandCursor = false; - - /** - * @property {boolean} isDragged - Description. - * @default - */ - this.isDragged = false; - - /** - * @property {boolean} allowHorizontalDrag - Description. - * @default - */ - this.allowHorizontalDrag = true; - - /** - * @property {boolean} allowVerticalDrag - Description. - * @default - */ - this.allowVerticalDrag = true; - - /** - * @property {boolean} bringToTop - Description. - * @default - */ - this.bringToTop = false; - - /** - * @property {Description} snapOffset - Description. - * @default - */ - this.snapOffset = null; - - /** - * @property {boolean} snapOnDrag - Description. - * @default - */ - this.snapOnDrag = false; - - /** - * @property {boolean} snapOnRelease - Description. - * @default - */ - this.snapOnRelease = false; - - /** - * @property {number} snapX - Description. - * @default - */ - this.snapX = 0; - - /** - * @property {number} snapY - Description. - * @default - */ - this.snapY = 0; - - /** - * @property {number} pixelPerfect - Should we use pixel perfect hit detection? Warning: expensive. Only enable if you really need it! - * @default - */ - this.pixelPerfect = false; - - /** - * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit. - * @default - */ - this.pixelPerfectAlpha = 255; - - /** - * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no - * @default - */ - this.draggable = false; - - /** - * @property {Description} boundsRect - A region of the game world within which the sprite is restricted during drag. - * @default - */ - this.boundsRect = null; - - /** - * @property {Description} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag. - * @default - */ - this.boundsSprite = null; - - /** - * If this object is set to consume the pointer event then it will stop all propogation from this object on. - * For example if you had a stack of 6 sprites with the same priority IDs and one consumed the event, none of the others would receive it. - * @property {boolean} consumePointerEvent - * @default - */ - this.consumePointerEvent = false; - - /** - * @property {Phaser.Point} _tempPoint - Description. - * @private - */ - this._tempPoint = new Phaser.Point; - - this._pointerData = []; - - this._pointerData.push({ - id: 0, - x: 0, - y: 0, - isDown: false, - isUp: false, - isOver: false, - isOut: false, - timeOver: 0, - timeOut: 0, - timeDown: 0, - timeUp: 0, - downDuration: 0, - isDragged: false - }); - -}; - -Phaser.InputHandler.prototype = { - - /** - * Description. - * @method Phaser.InputHandler#start - * @param {number} priority - Description. - * @param {boolean} useHandCursor - Description. - * @return {Phaser.Sprite} Description. - */ - start: function (priority, useHandCursor) { - - priority = priority || 0; - if (typeof useHandCursor == 'undefined') { useHandCursor = false; } - - // Turning on - if (this.enabled == false) - { - // Register, etc - this.game.input.interactiveItems.add(this); - this.useHandCursor = useHandCursor; - this.priorityID = priority; - - for (var i = 0; i < 10; i++) - { - this._pointerData[i] = { - id: i, - x: 0, - y: 0, - isDown: false, - isUp: false, - isOver: false, - isOut: false, - timeOver: 0, - timeOut: 0, - timeDown: 0, - timeUp: 0, - downDuration: 0, - isDragged: false - }; - } - - this.snapOffset = new Phaser.Point; - this.enabled = true; - - // Create the signals the Input component will emit - if (this.sprite.events && this.sprite.events.onInputOver == null) - { - this.sprite.events.onInputOver = new Phaser.Signal; - this.sprite.events.onInputOut = new Phaser.Signal; - this.sprite.events.onInputDown = new Phaser.Signal; - this.sprite.events.onInputUp = new Phaser.Signal; - this.sprite.events.onDragStart = new Phaser.Signal; - this.sprite.events.onDragStop = new Phaser.Signal; - } - } - - return this.sprite; - - }, - - /** - * Description. - * @method Phaser.InputHandler#reset - */ - reset: function () { - - this.enabled = false; - - for (var i = 0; i < 10; i++) - { - this._pointerData[i] = { - id: i, - x: 0, - y: 0, - isDown: false, - isUp: false, - isOver: false, - isOut: false, - timeOver: 0, - timeOut: 0, - timeDown: 0, - timeUp: 0, - downDuration: 0, - isDragged: false - }; - } - }, - - /** - * Description. - * @method Phaser.InputHandler#stop - */ - stop: function () { - - // Turning off - if (this.enabled == false) - { - return; - } - else - { - // De-register, etc - this.enabled = false; - this.game.input.interactiveItems.remove(this); - } - - }, - - /** - * Clean up memory. - * @method Phaser.InputHandler#destroy - */ - destroy: function () { - - if (this.enabled) - { - this.enabled = false; - - this.game.input.interactiveItems.remove(this); - - this.stop(); - - this.sprite = null; - } - }, - - /** - * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite. - * This value is only set when the pointer is over this Sprite. - * @method Phaser.InputHandler#pointerX - * @param {Pointer} pointer - * @return {number} The x coordinate of the Input pointer. - */ - pointerX: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].x; - - }, - - /** - * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite - * This value is only set when the pointer is over this Sprite. - * @method Phaser.InputHandler#pointerY - * @param {Pointer} pointer - * @return {number} The y coordinate of the Input pointer. - */ - pointerY: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].y; - - }, - - /** - * If the Pointer is touching the touchscreen, or the mouse button is held down, isDown is set to true. - * @method Phaser.InputHandler#pointerDown - * @param {Pointer} pointer - * @return {boolean} - */ - pointerDown: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].isDown; - - }, - - /** - * If the Pointer is not touching the touchscreen, or the mouse button is up, isUp is set to true - * @method Phaser.InputHandler#pointerUp - * @param {Pointer} pointer - * @return {boolean} - */ - pointerUp: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].isUp; - - }, - - /** - * A timestamp representing when the Pointer first touched the touchscreen. - * @method Phaser.InputHandler#pointerTimeDown - * @param {Pointer} pointer - * @return {number} - */ - pointerTimeDown: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].timeDown; - - }, - - /** - * A timestamp representing when the Pointer left the touchscreen. - * @method Phaser.InputHandler#pointerTimeUp - * @param {Pointer} pointer - * @return {number} - */ - pointerTimeUp: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].timeUp; - - }, - - /** - * Is the Pointer over this Sprite? - * @method Phaser.InputHandler#pointerOver - * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. - * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is over this object. - */ - pointerOver: function (index) { - - if (this.enabled) - { - if (typeof index === 'undefined') - { - for (var i = 0; i < 10; i++) - { - if (this._pointerData[i].isOver) - { - return true; - } - } - } - else - { - return this._pointerData[index].isOver; - } - } - - return false; - - }, - - /** - * Is the Pointer outside of this Sprite? - * @method Phaser.InputHandler#pointerOut - * @param {number} [index] - The ID number of a Pointer to check. If you don't provide a number it will check all Pointers. - * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object. - */ - pointerOut: function (pointer) { - - if (this.enabled) - { - if (typeof index === 'undefined') - { - for (var i = 0; i < 10; i++) - { - if (this._pointerData[i].isOut) - { - return true; - } - } - } - else - { - return this._pointerData[index].isOut; - } - } - - return false; - - }, - - /** - * A timestamp representing when the Pointer first touched the touchscreen. - * @method Phaser.InputHandler#pointerTimeOver - * @param {Pointer} pointer - * @return {number} - */ - pointerTimeOver: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].timeOver; - - }, - - /** - * A timestamp representing when the Pointer left the touchscreen. - * @method Phaser.InputHandler#pointerTimeOut - * @param {Pointer} pointer - * @return {number} - */ - pointerTimeOut: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].timeOut; - - }, - - /** - * Is this sprite being dragged by the mouse or not? - * @method Phaser.InputHandler#pointerTimeOut - * @param {Pointer} pointer - * @return {number} - */ - pointerDragged: function (pointer) { - - pointer = pointer || 0; - - return this._pointerData[pointer].isDragged; - - }, - - /** - * Checks if the given pointer is over this Sprite. - * @method Phaser.InputHandler#checkPointerOver - * @param {Pointer} pointer - * @return {boolean} - */ - checkPointerOver: function (pointer) { - - if (this.enabled && this.sprite.visible) - { - this.sprite.getLocalUnmodifiedPosition(this._tempPoint, pointer.x, pointer.y); - - if (this._tempPoint.x >= 0 && this._tempPoint.x <= this.sprite.currentFrame.width && this._tempPoint.y >= 0 && this._tempPoint.y <= this.sprite.currentFrame.height) - { - if (this.pixelPerfect) - { - return this.checkPixel(this._tempPoint.x, this._tempPoint.y); - } - else - { - return true; - } - } - } - - return false; - - }, - - /** - * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to. - * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true. - * @method Phaser.InputHandler#checkPixel - * @param {number} x - The x coordinate to check. - * @param {number} y - The y coordinate to check. - * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha - */ - checkPixel: function (x, y) { - - // Grab a pixel from our image into the hitCanvas and then test it - if (this.sprite.texture.baseTexture.source) - { - this.game.input.hitContext.clearRect(0, 0, 1, 1); - - x += this.sprite.texture.frame.x; - y += this.sprite.texture.frame.y; - - this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1); - - var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1); - - if (rgb.data[3] >= this.pixelPerfectAlpha) - { - return true; - } - } - - return false; - - }, - - /** - * Update. - * @method Phaser.InputHandler#update - * @param {Pointer} pointer - */ - update: function (pointer) { - - if (this.enabled == false || this.sprite.visible == false || (this.sprite.group && this.sprite.group.visible == false)) - { - this._pointerOutHandler(pointer); - return false; - } - - if (this.draggable && this._draggedPointerID == pointer.id) - { - return this.updateDrag(pointer); - } - else if (this._pointerData[pointer.id].isOver == true) - { - if (this.checkPointerOver(pointer)) - { - this._pointerData[pointer.id].x = pointer.x - this.sprite.x; - this._pointerData[pointer.id].y = pointer.y - this.sprite.y; - return true; - } - else - { - this._pointerOutHandler(pointer); - return false; - } - } - }, - - /** - * Description. - * @method Phaser.InputHandler#_pointerOverHandler - * @private - * @param {Pointer} pointer - */ - _pointerOverHandler: function (pointer) { - - if (this._pointerData[pointer.id].isOver == false) - { - this._pointerData[pointer.id].isOver = true; - this._pointerData[pointer.id].isOut = false; - this._pointerData[pointer.id].timeOver = this.game.time.now; - this._pointerData[pointer.id].x = pointer.x - this.sprite.x; - this._pointerData[pointer.id].y = pointer.y - this.sprite.y; - - if (this.useHandCursor && this._pointerData[pointer.id].isDragged == false) - { - this.game.stage.canvas.style.cursor = "pointer"; - } - - this.sprite.events.onInputOver.dispatch(this.sprite, pointer); - } - }, - - /** - * Description. - * @method Phaser.InputHandler#_pointerOutHandler - * @private - * @param {Pointer} pointer - */ - _pointerOutHandler: function (pointer) { - - this._pointerData[pointer.id].isOver = false; - this._pointerData[pointer.id].isOut = true; - this._pointerData[pointer.id].timeOut = this.game.time.now; - - if (this.useHandCursor && this._pointerData[pointer.id].isDragged == false) - { - this.game.stage.canvas.style.cursor = "default"; - } - - if (this.sprite && this.sprite.events) - { - this.sprite.events.onInputOut.dispatch(this.sprite, pointer); - } - - }, - - /** - * Description. - * @method Phaser.InputHandler#_touchedHandler - * @private - * @param {Pointer} pointer - */ - _touchedHandler: function (pointer) { - - if (this._pointerData[pointer.id].isDown == false && this._pointerData[pointer.id].isOver == true) - { - this._pointerData[pointer.id].isDown = true; - this._pointerData[pointer.id].isUp = false; - this._pointerData[pointer.id].timeDown = this.game.time.now; - this.sprite.events.onInputDown.dispatch(this.sprite, pointer); - - // Start drag - if (this.draggable && this.isDragged == false) - { - this.startDrag(pointer); - } - - if (this.bringToTop) - { - this.sprite.bringToTop(); - } - } - - // Consume the event? - return this.consumePointerEvent; - - }, - - /** - * Description. - * @method Phaser.InputHandler#_releasedHandler - * @private - * @param {Pointer} pointer - */ - _releasedHandler: function (pointer) { - - // If was previously touched by this Pointer, check if still is AND still over this item - if (this._pointerData[pointer.id].isDown && pointer.isUp) - { - this._pointerData[pointer.id].isDown = false; - this._pointerData[pointer.id].isUp = true; - this._pointerData[pointer.id].timeUp = this.game.time.now; - this._pointerData[pointer.id].downDuration = this._pointerData[pointer.id].timeUp - this._pointerData[pointer.id].timeDown; - - // Only release the InputUp signal if the pointer is still over this sprite - if (this.checkPointerOver(pointer)) - { - //console.log('releasedHandler: ' + Date.now()); - this.sprite.events.onInputUp.dispatch(this.sprite, pointer); - } - else - { - // Pointer outside the sprite? Reset the cursor - if (this.useHandCursor) - { - this.game.stage.canvas.style.cursor = "default"; - } - } - - // Stop drag - if (this.draggable && this.isDragged && this._draggedPointerID == pointer.id) - { - this.stopDrag(pointer); - } - } - - }, - - /** - * Updates the Pointer drag on this Sprite. - * @method Phaser.InputHandler#updateDrag - * @param {Pointer} pointer - * @return {boolean} - */ - updateDrag: function (pointer) { - - if (pointer.isUp) - { - this.stopDrag(pointer); - return false; - } - - if (this.allowHorizontalDrag) - { - this.sprite.x = pointer.x + this._dragPoint.x + this.dragOffset.x; - } - - if (this.allowVerticalDrag) - { - this.sprite.y = pointer.y + this._dragPoint.y + this.dragOffset.y; - } - - if (this.boundsRect) - { - this.checkBoundsRect(); - } - - if (this.boundsSprite) - { - this.checkBoundsSprite(); - } - - if (this.snapOnDrag) - { - this.sprite.x = Math.round(this.sprite.x / this.snapX) * this.snapX; - this.sprite.y = Math.round(this.sprite.y / this.snapY) * this.snapY; - } - - return true; - - }, - - /** - * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) - * @method Phaser.InputHandler#justOver - * @param {Pointer} pointer - * @param {number} delay - The time below which the pointer is considered as just over. - * @return {boolean} - */ - justOver: function (pointer, delay) { - - pointer = pointer || 0; - delay = delay || 500; - - return (this._pointerData[pointer].isOver && this.overDuration(pointer) < delay); - - }, - - /** - * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) - * @method Phaser.InputHandler#justOut - * @param {Pointer} pointer - * @param {number} delay - The time below which the pointer is considered as just out. - * @return {boolean} - */ - justOut: function (pointer, delay) { - - pointer = pointer || 0; - delay = delay || 500; - - return (this._pointerData[pointer].isOut && (this.game.time.now - this._pointerData[pointer].timeOut < delay)); - - }, - - /** - * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second) - * @method Phaser.InputHandler#justPressed - * @param {Pointer} pointer - * @param {number} delay - The time below which the pointer is considered as just over. - * @return {boolean} - */ - justPressed: function (pointer, delay) { - - pointer = pointer || 0; - delay = delay || 500; - - return (this._pointerData[pointer].isDown && this.downDuration(pointer) < delay); - - }, - - /** - * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second) - * @method Phaser.InputHandler#justReleased - * @param {Pointer} pointer - * @param {number} delay - The time below which the pointer is considered as just out. - * @return {boolean} - */ - justReleased: function (pointer, delay) { - - pointer = pointer || 0; - delay = delay || 500; - - return (this._pointerData[pointer].isUp && (this.game.time.now - this._pointerData[pointer].timeUp < delay)); - - }, - - /** - * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. - * @method Phaser.InputHandler#overDuration - * @param {Pointer} pointer - * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over. - */ - overDuration: function (pointer) { - - pointer = pointer || 0; - - if (this._pointerData[pointer].isOver) - { - return this.game.time.now - this._pointerData[pointer].timeOver; - } - - return -1; - - }, - - /** - * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds. - * @method Phaser.InputHandler#downDuration - * @param {Pointer} pointer - * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over. - */ - downDuration: function (pointer) { - - pointer = pointer || 0; - - if (this._pointerData[pointer].isDown) - { - return this.game.time.now - this._pointerData[pointer].timeDown; - } - - return -1; - - }, - - /** - * Make this Sprite draggable by the mouse. You can also optionally set mouseStartDragCallback and mouseStopDragCallback - * @method Phaser.InputHandler#enableDrag - * @param lockCenter If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer. - * @param bringToTop If true the Sprite will be bought to the top of the rendering list in its current Group. - * @param pixelPerfect If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box. - * @param alphaThreshold If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed (default 255) - * @param boundsRect If you want to restrict the drag of this sprite to a specific FlxRect, pass the FlxRect here, otherwise it's free to drag anywhere - * @param boundsSprite If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here - */ - enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) { - - if (typeof lockCenter == 'undefined') { lockCenter = false; } - if (typeof bringToTop == 'undefined') { bringToTop = false; } - if (typeof pixelPerfect == 'undefined') { pixelPerfect = false; } - - alphaThreshold = alphaThreshold || 255; - boundsRect = boundsRect || null; - boundsSprite = boundsSprite || null; - - this._dragPoint = new Phaser.Point(); - this.draggable = true; - this.bringToTop = bringToTop; - this.dragOffset = new Phaser.Point(); - this.dragFromCenter = lockCenter; - - this.pixelPerfect = pixelPerfect; - this.pixelPerfectAlpha = alphaThreshold; - - if (boundsRect) - { - this.boundsRect = boundsRect; - } - - if (boundsSprite) - { - this.boundsSprite = boundsSprite; - } - - }, - - /** - * Stops this sprite from being able to be dragged. If it is currently the target of an active drag it will be stopped immediately. Also disables any set callbacks. - * @method Phaser.InputHandler#disableDrag - */ - disableDrag: function () { - - if (this._pointerData) - { - for (var i = 0; i < 10; i++) - { - this._pointerData[i].isDragged = false; - } - } - - this.draggable = false; - this.isDragged = false; - this._draggedPointerID = -1; - - }, - - /** - * Called by Pointer when drag starts on this Sprite. Should not usually be called directly. - * @method Phaser.InputHandler#startDrag - */ - startDrag: function (pointer) { - - this.isDragged = true; - this._draggedPointerID = pointer.id; - this._pointerData[pointer.id].isDragged = true; - - if (this.dragFromCenter) - { - this.sprite.centerOn(pointer.x, pointer.y); - this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y); - } - else - { - this._dragPoint.setTo(this.sprite.x - pointer.x, this.sprite.y - pointer.y); - } - - this.updateDrag(pointer); - - if (this.bringToTop) - { - this.sprite.bringToTop(); - } - - this.sprite.events.onDragStart.dispatch(this.sprite, pointer); - - }, - - /** - * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly. - * @method Phaser.InputHandler#stopDrag - */ - stopDrag: function (pointer) { - - this.isDragged = false; - this._draggedPointerID = -1; - this._pointerData[pointer.id].isDragged = false; - - if (this.snapOnRelease) - { - this.sprite.x = Math.round(this.sprite.x / this.snapX) * this.snapX; - this.sprite.y = Math.round(this.sprite.y / this.snapY) * this.snapY; - } - - this.sprite.events.onDragStop.dispatch(this.sprite, pointer); - this.sprite.events.onInputUp.dispatch(this.sprite, pointer); - - if (this.checkPointerOver(pointer) == false) - { - this._pointerOutHandler(pointer); - } - - }, - - /** - * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move! - * @method Phaser.InputHandler#setDragLock - * @param allowHorizontal To enable the sprite to be dragged horizontally set to true, otherwise false - * @param allowVertical To enable the sprite to be dragged vertically set to true, otherwise false - */ - setDragLock: function (allowHorizontal, allowVertical) { - - if (typeof allowHorizontal == 'undefined') { allowHorizontal = true; } - if (typeof allowVertical == 'undefined') { allowVertical = true; } - - this.allowHorizontalDrag = allowHorizontal; - this.allowVerticalDrag = allowVertical; - - }, - - /** - * Make this Sprite snap to the given grid either during drag or when it's released. - * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels. - * @method Phaser.InputHandler#enableSnap - * @param snapX The width of the grid cell in pixels - * @param snapY The height of the grid cell in pixels - * @param onDrag If true the sprite will snap to the grid while being dragged - * @param onRelease If true the sprite will snap to the grid when released - */ - enableSnap: function (snapX, snapY, onDrag, onRelease) { - - if (typeof onDrag == 'undefined') { onDrag = true; } - if (typeof onRelease == 'undefined') { onRelease = false; } - - this.snapX = snapX; - this.snapY = snapY; - this.snapOnDrag = onDrag; - this.snapOnRelease = onRelease; - - }, - - /** - * Stops the sprite from snapping to a grid during drag or release. - * @method Phaser.InputHandler#disableSnap - */ - disableSnap: function () { - - this.snapOnDrag = false; - this.snapOnRelease = false; - - }, - - /** - * Bounds Rect check for the sprite drag - * @method Phaser.InputHandler#checkBoundsRect - */ - checkBoundsRect: function () { - - if (this.sprite.x < this.boundsRect.left) - { - this.sprite.x = this.boundsRect.x; - } - else if ((this.sprite.x + this.sprite.width) > this.boundsRect.right) - { - this.sprite.x = this.boundsRect.right - this.sprite.width; - } - - if (this.sprite.y < this.boundsRect.top) - { - this.sprite.y = this.boundsRect.top; - } - else if ((this.sprite.y + this.sprite.height) > this.boundsRect.bottom) - { - this.sprite.y = this.boundsRect.bottom - this.sprite.height; - } - - }, - - /** - * Parent Sprite Bounds check for the sprite drag. - * @method Phaser.InputHandler#checkBoundsSprite - */ - checkBoundsSprite: function () { - - if (this.sprite.x < this.boundsSprite.x) - { - this.sprite.x = this.boundsSprite.x; - } - else if ((this.sprite.x + this.sprite.width) > (this.boundsSprite.x + this.boundsSprite.width)) - { - this.sprite.x = (this.boundsSprite.x + this.boundsSprite.width) - this.sprite.width; - } - - if (this.sprite.y < this.boundsSprite.y) - { - this.sprite.y = this.boundsSprite.y; - } - else if ((this.sprite.y + this.sprite.height) > (this.boundsSprite.y + this.boundsSprite.height)) - { - this.sprite.y = (this.boundsSprite.y + this.boundsSprite.height) - this.sprite.height; - } - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - - -/** -* The Events component is a collection of events fired by the parent game object and its components. -* -* @class Phaser.Events -* @constructor -* -* @param {Phaser.Sprite} sprite - A reference to Description. -*/ -Phaser.Events = function (sprite) { - - this.parent = sprite; - this.onAddedToGroup = new Phaser.Signal; - this.onRemovedFromGroup = new Phaser.Signal; - this.onKilled = new Phaser.Signal; - this.onRevived = new Phaser.Signal; - this.onOutOfBounds = new Phaser.Signal; - - this.onInputOver = null; - this.onInputOut = null; - this.onInputDown = null; - this.onInputUp = null; - this.onDragStart = null; - this.onDragStop = null; - - this.onAnimationStart = null; - this.onAnimationComplete = null; - this.onAnimationLoop = null; - -}; - -Phaser.Events.prototype = { - - destroy: function () { - - this.parent = null; - this.onAddedToGroup.dispose(); - this.onRemovedFromGroup.dispose(); - this.onKilled.dispose(); - this.onRevived.dispose(); - this.onOutOfBounds.dispose(); - - if (this.onInputOver) - { - this.onInputOver.dispose(); - this.onInputOut.dispose(); - this.onInputDown.dispose(); - this.onInputUp.dispose(); - this.onDragStart.dispose(); - this.onDragStop.dispose(); - } - - if (this.onAnimationStart) - { - this.onAnimationStart.dispose(); - this.onAnimationComplete.dispose(); - this.onAnimationLoop.dispose(); - } - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Game Object Factory is a quick way to create all of the different sorts of core objects that Phaser uses. -* -* @class Phaser.GameObjectFactory -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.GameObjectFactory = function (game) { - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {Phaser.World} world - A reference to the game world. - */ - this.world = this.game.world; - -}; - -Phaser.GameObjectFactory.prototype = { - - /** - * Adds an existing object to the game world. - * @method Phaser.GameObjectFactory#existing - * @param {*} object - An instance of Phaser.Sprite, Phaser.Button or any other display object.. - * @return {*} The child that was added to the Group. - */ - existing: function (object) { - - return this.world.add(object); - - }, - - /** - * Create a new Sprite with specific position and sprite sheet key. - * - * @method Phaser.GameObjectFactory#sprite - * @param {number} x - X position of the new sprite. - * @param {number} y - Y position of the new sprite. - * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. - * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. - * @returns {Phaser.Sprite} the newly created sprite object. - */ - sprite: function (x, y, key, frame) { - - return this.world.create(x, y, key, frame); - - }, - - /** - * Create a new Sprite with specific position and sprite sheet key that will automatically be added as a child of the given parent. - * - * @method Phaser.GameObjectFactory#child - * @param {Phaser.Group} group - The Group to add this child to. - * @param {number} x - X position of the new sprite. - * @param {number} y - Y position of the new sprite. - * @param {string|RenderTexture} [key] - The image key as defined in the Game.Cache to use as the texture for this sprite OR a RenderTexture. - * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name. - * @returns {Phaser.Sprite} the newly created sprite object. - */ - child: function (group, x, y, key, frame) { - - return group.create(x, y, key, frame); - - }, - - /** - * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. - * - * @method Phaser.GameObjectFactory#tween - * @param {object} obj - Object the tween will be run on. - * @return {Phaser.Tween} Description. - */ - tween: function (obj) { - - return this.game.tweens.create(obj); - - }, - - /** - * A Group is a container for display objects that allows for fast pooling, recycling and collision checks. - * - * @method Phaser.GameObjectFactory#group - * @param {*} parent - The parent Group or DisplayObjectContainer that will hold this group, if any. - * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging. - * @return {Phaser.Group} The newly created group. - */ - group: function (parent, name) { - - return new Phaser.Group(this.game, parent, name); - - }, - - /** - * Creates a new instance of the Sound class. - * - * @method Phaser.GameObjectFactory#audio - * @param {string} key - The Game.cache key of the sound that this object will use. - * @param {number} volume - The volume at which the sound will be played. - * @param {boolean} loop - Whether or not the sound will loop. - * @return {Phaser.Sound} The newly created text object. - */ - audio: function (key, volume, loop) { - - return this.game.sound.add(key, volume, loop); - - }, - - /** - * Creates a new TileSprite. - * - * @method Phaser.GameObjectFactory#tileSprite - * @param {number} x - X position of the new tileSprite. - * @param {number} y - Y position of the new tileSprite. - * @param {number} width - the width of the tilesprite. - * @param {number} height - the height of the tilesprite. - * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. - * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. - * @return {Phaser.TileSprite} The newly created tileSprite object. - */ - tileSprite: function (x, y, width, height, key, frame) { - - return this.world.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame)); - - }, - - /** - * Creates a new Text. - * - * @method Phaser.GameObjectFactory#text - * @param {number} x - X position of the new text object. - * @param {number} y - Y position of the new text object. - * @param {string} text - The actual text that will be written. - * @param {object} style - The style object containing style attributes like font, font size , etc. - * @return {Phaser.Text} The newly created text object. - */ - text: function (x, y, text, style) { - - return this.world.add(new Phaser.Text(this.game, x, y, text, style)); - - }, - - /** - * Creates a new Button object. - * - * @method Phaser.GameObjectFactory#button - * @param {number} [x] X position of the new button object. - * @param {number} [y] Y position of the new button object. - * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button. - * @param {function} [callback] The function to call when this button is pressed - * @param {object} [callbackContext] The context in which the callback will be called (usually 'this') - * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. - * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. - * @return {Phaser.Button} The newly created button object. - */ - button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame) { - - return this.world.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame)); - - }, - - /** - * Creates a new Graphics object. - * - * @method Phaser.GameObjectFactory#graphics - * @param {number} x - X position of the new graphics object. - * @param {number} y - Y position of the new graphics object. - * @return {Phaser.Graphics} The newly created graphics object. - */ - graphics: function (x, y) { - - return this.world.add(new Phaser.Graphics(this.game, x, y)); - - }, - - /** - * Emitter is a lightweight particle emitter. It can be used for one-time explosions or for - * continuous effects like rain and fire. All it really does is launch Particle objects out - * at set intervals, and fixes their positions and velocities accorindgly. - * - * @method Phaser.GameObjectFactory#emitter - * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. - * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. - * @param {number} [maxParticles=50] - The total number of particles in this emitter. - * @return {Phaser.Emitter} The newly created emitter object. - */ - emitter: function (x, y, maxParticles) { - - return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles)); - - }, - - /** - * * Create a new BitmapText. - * - * @method Phaser.GameObjectFactory#bitmapText - * @param {number} x - X position of the new bitmapText object. - * @param {number} y - Y position of the new bitmapText object. - * @param {string} text - The actual text that will be written. - * @param {object} style - The style object containing style attributes like font, font size , etc. - * @return {Phaser.BitmapText} The newly created bitmapText object. - */ - bitmapText: function (x, y, text, style) { - - return this.world.add(new Phaser.BitmapText(this.game, x, y, text, style)); - - }, - - /** - * Creates a new Tilemap object. - * - * @method Phaser.GameObjectFactory#tilemap - * @param {string} key - Asset key for the JSON file. - * @return {Phaser.Tilemap} The newly created tilemap object. - */ - tilemap: function (key) { - - return new Phaser.Tilemap(this.game, key); - - }, - - /** - * Creates a new Tileset object. - * - * @method Phaser.GameObjectFactory#tileset - * @param {string} key - The image key as defined in the Game.Cache to use as the tileset. - * @return {Phaser.Tileset} The newly created tileset object. - */ - tileset: function (key) { - - return this.game.cache.getTileset(key); - - }, - - /** - * Creates a new Tilemap Layer object. - * - * @method Phaser.GameObjectFactory#tilemapLayer - * @param {number} x - X position of the new tilemapLayer. - * @param {number} y - Y position of the new tilemapLayer. - * @param {number} width - the width of the tilemapLayer. - * @param {number} height - the height of the tilemapLayer. - * @return {Phaser.TilemapLayer} The newly created tilemaplayer object. - */ - tilemapLayer: function (x, y, width, height, tileset, tilemap, layer) { - - return this.world.add(new Phaser.TilemapLayer(this.game, x, y, width, height, tileset, tilemap, layer)); - - }, - - /** - * A dynamic initially blank canvas to which images can be drawn. - * - * @method Phaser.GameObjectFactory#renderTexture - * @param {string} key - Asset key for the render texture. - * @param {number} width - the width of the render texture. - * @param {number} height - the height of the render texture. - * @return {Phaser.RenderTexture} The newly created renderTexture object. - */ - renderTexture: function (key, width, height) { - - var texture = new Phaser.RenderTexture(this.game, key, width, height); - - this.game.cache.addRenderTexture(key, texture); - - return texture; - - }, - - /** - * A BitmapData object which can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites. - * - * @method Phaser.GameObjectFactory#bitmapData - * @param {number} [width=256] - The width of the BitmapData in pixels. - * @param {number} [height=256] - The height of the BitmapData in pixels. - * @return {Phaser.BitmapData} The newly created BitmapData object. - */ - bitmapData: function (width, height) { - - return new Phaser.BitmapData(this.game, width, height); - - }, - - /** - * A WebGL shader/filter that can be applied to Sprites. - * - * @method Phaser.GameObjectFactory#filter - * @param {string} filter - The name of the filter you wish to create, for example "HueRotate" or "SineWave" - * @param {...} - Whatever parameters are needed to be passed to the filter init function. - * @return {Phaser.Filter} The newly created Phaser.Filter object. - */ - filter: function (filter) { - - var args = Array.prototype.splice.call(arguments, 1); - - var f = new Phaser.Filter[filter](this.game); - - f.init.apply(f, args); - - return f; - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new `BitmapData` object. -* -* @class Phaser.BitmapData -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} [width=256] - The width of the BitmapData in pixels. -* @param {number} [height=256] - The height of the BitmapData in pixels. -*/ -Phaser.BitmapData = function (game, width, height) { - - if (typeof width === 'undefined') { width = 256; } - if (typeof height === 'undefined') { height = 256; } - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {string} name - The name of the BitmapData. - */ - this.name = ''; - - /** - * @property {number} width - The width of the BitmapData in pixels. - */ - this.width = width; - - /** - * @property {number} height - The height of the BitmapData in pixels. - */ - this.height = height; - - /** - * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws. - * @default - */ - this.canvas = Phaser.Canvas.create(width, height); - - /** - * @property {CanvasRenderingContext2D} context - The 2d context of the canvas. - * @default - */ - this.context = this.canvas.getContext('2d'); - - /** - * @property {array} imageData - The canvas image data. - */ - this.imageData = this.context.getImageData(0, 0, width, height); - - /** - * @property {UInt8Clamped} pixels - A reference to the context imageData buffer. - */ - if (this.imageData.data.buffer) - { - this.pixels = this.imageData.data.buffer; - } - else - { - this.pixels = this.imageData.data; - } - - /** - * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture. - * @default - */ - this.baseTexture = new PIXI.BaseTexture(this.canvas); - - /** - * @property {PIXI.Texture} texture - The PIXI.Texture. - * @default - */ - this.texture = new PIXI.Texture(this.baseTexture); - - /** - * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering. - * @default - */ - this.textureFrame = new Phaser.Frame(0, 0, 0, width, height, 'bitmapData', game.rnd.uuid()); - - /** - * @property {number} type - The const type of this object. - * @default - */ - this.type = Phaser.BITMAPDATA; - - this._dirty = false; - -} - -Phaser.BitmapData.prototype = { - - /** - * Updates the given Sprite so that it uses this BitmapData as its texture. - * @method Phaser.BitmapData.add - * @param {Phaser.Sprite} sprite - The sprite to apply this texture to. - */ - add: function (sprite) { - - sprite.loadTexture(this); - - }, - - /** - * Given an array of Sprites it will update each of them so that their Textures reference this BitmapData. - * @method Phaser.BitmapData.addTo - * @param {Phaser.Sprite[]} sprites - An array of Sprites to apply this texture to. - */ - addTo: function (sprites) { - - for (var i = 0; i < objects.length; i++) - { - if (objects[i].texture) - { - } - } - - }, - - /** - * Clears the BitmapData. - * @method Phaser.BitmapData.clear - */ - clear: function () { - - this.context.clearRect(0, 0, this.width, this.height); - - this._dirty = true; - - }, - - refreshBuffer: function () { - - this.imageData = this.context.getImageData(0, 0, this.width, this.height); - this.pixels = new Int32Array(this.imageData.data.buffer); - - // this.data8 = new Uint8ClampedArray(this.imageData.buffer); - // this.data32 = new Uint32Array(this.imageData.buffer); - - }, - - /** - * Sets the color of the given pixel to the specified red, green, blue and alpha values. - * @method Phaser.BitmapData.setPixel32 - * @param {number} x - The X coordinate of the pixel to be set. - * @param {number} y - The Y coordinate of the pixel to be set. - * @param {number} red - The red color value, between 0 and 0xFF (255). - * @param {number} green - The green color value, between 0 and 0xFF (255). - * @param {number} blue - The blue color value, between 0 and 0xFF (255). - * @param {number} alpha - The alpha color value, between 0 and 0xFF (255). - */ - setPixel32: function (x, y, red, green, blue, alpha) { - - if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) - { - this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red; - - /* - if (this.isLittleEndian) - { - this.data32[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red; - } - else - { - this.data32[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha; - } - */ - - // this.imageData.data.set(this.data8); - - this.context.putImageData(this.imageData, 0, 0); - - this._dirty = true; - } - - }, - - /** - * Sets the color of the given pixel to the specified red, green and blue values. - * @method Phaser.BitmapData.setPixel - * @param {number} x - The X coordinate of the pixel to be set. - * @param {number} y - The Y coordinate of the pixel to be set. - * @param {number} red - The red color value (between 0 and 255) - * @param {number} green - The green color value (between 0 and 255) - * @param {number} blue - The blue color value (between 0 and 255) - */ - setPixel: function (x, y, red, green, blue) { - - this.setPixel32(x, y, red, green, blue, 255); - - }, - - /** - * Get a color of a specific pixel. - * @param {number} x - The X coordinate of the pixel to get. - * @param {number} y - The Y coordinate of the pixel to get. - * @return {number} A native color value integer (format: 0xRRGGBB) - */ - getPixel: function (x, y) { - - if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) - { - return this.data32[y * this.width + x]; - } - - }, - - /** - * Get a color of a specific pixel (including alpha value). - * @param {number} x - The X coordinate of the pixel to get. - * @param {number} y - The Y coordinate of the pixel to get. - * @return {number} A native color value integer (format: 0xAARRGGBB) - */ - getPixel32: function (x, y) { - - if (x >= 0 && x <= this.width && y >= 0 && y <= this.height) - { - return this.data32[y * this.width + x]; - } - - }, - - /** - * Get pixels in array in a specific Rectangle. - * @param rect {Rectangle} The specific Rectangle. - * @return {array} CanvasPixelArray. - */ - getPixels: function (rect) { - - // return this.context.getImageData(rect.x, rect.y, rect.width, rect.height); - - }, - - /** - * Adds an arc to the path which is centered at (x, y) position with radius r starting at startAngle and ending at endAngle - * going in the given direction by anticlockwise (defaulting to clockwise). - * @method Phaser.BitmapData.arc - * @param {number} x - The x axis of the coordinate for the arc's center - * @param {number} y - The y axis of the coordinate for the arc's center - * @param {number} radius - The arc's radius - * @param {number} startAngle - The starting point, measured from the x axis, from which it will be drawn, expressed in radians. - * @param {number} endAngle - The end arc's angle to which it will be drawn, expressed in radians. - * @param {boolean} [anticlockwise=true] - true draws the arc anticlockwise, otherwise in a clockwise direction. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - arc: function (x, y, radius, startAngle, endAngle, anticlockwise) { - - if (typeof anticlockwise === 'undefined') { anticlockwise = false; } - - this._dirty = true; - this.context.arc(x, y, radius, startAngle, endAngle, anticlockwise); - return this; - - }, - - /** - * Adds an arc with the given control points and radius, connected to the previous point by a straight line. - * @method Phaser.BitmapData.arcTo - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @param {number} radius - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - arcTo: function (x1, y1, x2, y2, radius) { - - this._dirty = true; - this.context.arcTo(x1, y1, x2, y2, radius); - return this; - - }, - - /** - * Begins a fill with the specified color. This ends the current sub-path. - * @method Phaser.BitmapData.beginFill - * @param {string} color - A CSS compatible color value (ex. "red", "#FF0000", or "rgba(255,0,0,0.5)"). Setting to null will result in no fill. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - beginFill: function (color) { - - this.fillStyle(color); - - return this; - - }, - - /** - * Begins a linear gradient fill defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For - * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a square to display it: - * - * ```myGraphics.beginLinearGradientFill(["#000","#FFF"], [0, 1], 0, 20, 0, 120).rect(20, 20, 120, 120);``` - * - * @method Phaser.BitmapData.beginLinearGradientFill - * @param {Array} colors - An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient drawing from red to blue. - * @param {Array} ratios - An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {number} x0 - The position of the first point defining the line that defines the gradient direction and size. - * @param {number} y0 - The position of the first point defining the line that defines the gradient direction and size. - * @param {number} x1 - The position of the second point defining the line that defines the gradient direction and size. - * @param {number} y1 - The position of the second point defining the line that defines the gradient direction and size. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - beginLinearGradientFill: function (colors, ratios, x0, y0, x1, y1) { - - var gradient = this.createLinearGradient(x0, y0, x1, y1); - - for (var i = 0, len = colors.length; i < len; i++) - { - gradient.addColorStop(ratios[i], colors[i]); - } - - this.fillStyle(gradient); - - return this; - - }, - - /** - * Begins a linear gradient stroke defined by the line (x0, y0) to (x1, y1). This ends the current sub-path. For - * example, the following code defines a black to white vertical gradient ranging from 20px to 120px, and draws a - * square to display it: - * - * ```myGraphics.setStrokeStyle(10).beginLinearGradientStroke(["#000","#FFF"], [0, 1], 0, 20, 0, 120).drawRect(20, 20, 120, 120);``` - * - * @method Phaser.BitmapData.beginLinearGradientStroke - * @param {Array} colors - An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient drawing from red to blue. - * @param {Array} ratios - An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {number} x0 - The position of the first point defining the line that defines the gradient direction and size. - * @param {number} y0 - The position of the first point defining the line that defines the gradient direction and size. - * @param {number} x1 - The position of the second point defining the line that defines the gradient direction and size. - * @param {number} y1 - The position of the second point defining the line that defines the gradient direction and size. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - beginLinearGradientStroke: function (colors, ratios, x0, y0, x1, y1) { - - var gradient = this.createLinearGradient(x0, y0, x1, y1); - - for (var i = 0, len = colors.length; i < len; i++) - { - gradient.addColorStop(ratios[i], colors[i]); - } - - this.strokeStyle(gradient); - - return this; - - }, - - /** - * Begins a radial gradient stroke. This ends the current sub-path. For example, the following code defines a red to - * blue radial gradient centered at (100, 100), with a radius of 50, and draws a rectangle to display it: - * - * myGraphics.setStrokeStyle(10) - * .beginRadialGradientStroke(["#F00","#00F"], [0, 1], 100, 100, 0, 100, 100, 50) - * .drawRect(50, 90, 150, 110); - * - * @method Phaser.BitmapData.beginRadialGradientStroke - * @param {Array} colors - An array of CSS compatible color values. For example, ["#F00","#00F"] would define a gradient drawing from red to blue. - * @param {Array} ratios - An array of gradient positions which correspond to the colors. For example, [0.1, 0.9] would draw the first color to 10% then interpolating to the second color at 90%. - * @param {number} x0 - Center position of the inner circle that defines the gradient. - * @param {number} y0 - Center position of the inner circle that defines the gradient. - * @param {number} r0 - Radius of the inner circle that defines the gradient. - * @param {number} x1 - Center position of the outer circle that defines the gradient. - * @param {number} y1 - Center position of the outer circle that defines the gradient. - * @param {number} r1 - Radius of the outer circle that defines the gradient. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - beginRadialGradientStroke: function (colors, ratios, x0, y0, r0, x1, y1, r1) { - - var gradient = this.createRadialGradient(x0, y0, r0, x1, y1, r1); - - for (var i = 0, len = colors.length; i < len; i++) - { - gradient.addColorStop(ratios[i], colors[i]); - } - - this.strokeStyle(gradient); - - return this; - - }, - - /** - * Starts a new path by resetting the list of sub-paths. Call this method when you want to create a new path. - * @method Phaser.BitmapData.beginPath - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - beginPath: function () { - - this.context.beginPath(); - return this; - - }, - - /** - * Begins a stroke with the specified color. This ends the current sub-path. - * @method Phaser.BitmapData.beginStroke - * @param {String} color A CSS compatible color value (ex. "#FF0000", "red", or "rgba(255,0,0,0.5)"). Setting to null will result in no stroke. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - beginStroke: function (color) { - - this.strokeStyle(color); - return this; - - }, - - /** - * Adds a bezier curve from the current context point to (x, y) using the control points (cp1x, cp1y) and (cp2x, cp2y). - * @method Phaser.BitmapData.bezierCurveTo - * @param {number} cp1x - The x axis of control point 1. - * @param {number} cp1y - The y axis of control point 1. - * @param {number} cp2x - The x axis of control point 2. - * @param {number} cp2y - The y axis of control point 2. - * @param {number} x - The x axis of the ending point. - * @param {number} y - The y axis of the ending point. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - bezierCurveTo: function (cp1x, cp1y, cp2x, cp2y, x, y) { - - this._dirty = true; - this.context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y); - return this; - - }, - - /** - * Draws a circle with the specified radius at (x, y). - * @method Phaser.BitmapData.circle - * @param {number} x - x coordinate center point of circle. - * @param {number} y - y coordinate center point of circle. - * @param {number} radius - Radius of circle in radians. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - circle: function (x, y, radius) { - - this.arc(x, y, radius, 0, Math.PI*2); - return this; - - }, - - /** - * Sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black. - * @method Phaser.BitmapData.clearRect - * @param {number} x - The x axis of the coordinate for the rectangle starting point. - * @param {number} y - The y axis of the coordinate for the rectangle starting point. - * @param {number} width - The rectangles width. - * @param {number} height - The rectangles height. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - clearRect: function (x, y, width, height) { - - this._dirty = true; - this.context.clearRect(x, y, width, height); - return this; - - }, - - /** - * Creates a clipping path from the current sub-paths. Everything drawn after clip() is called appears inside the clipping path only. - * @method Phaser.BitmapData.clip - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - clip: function (x, y, width, height) { - - this._dirty = true; - this.context.clip(); - return this; - - }, - - /** - * Tries to draw a straight line from the current point to the start. If the shape has already been closed or has only one point, this function does nothing. - * @method Phaser.BitmapData.closePath - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - closePath: function () { - - this._dirty = true; - this.context.closePath(); - return this; - - }, - - /** - * Creates a linear gradient with defined by an imaginary line which implies the direction of the gradient. - * Once the gradient is created colors can be inserted using the addColorStop method. - * @method Phaser.BitmapData.createLinearGradient - * @param {number} x - The x axis of the coordinate for the gradients starting point. - * @param {number} y - The y axis of the coordinate for the gradients starting point. - * @param {number} width - The width of the gradient. - * @param {number} height - The height of the gradient. - * @return {CanvasGradient} The Linear Gradient. - */ - createLinearGradient: function (x, y, width, height) { - - return this.context.createLinearGradient(x, y, width, height); - - }, - - // createPattern - - /** - * Creates a radial gradient. - * @method Phaser.BitmapData.createRadialGradient - * @param {number} x0 - * @param {number} y0 - * @param {number} r0 - * @param {number} x1 - * @param {number} y1 - * @param {number} r1 - * @return {CanvasGradient} The Radial Gradient. - */ - createRadialGradient: function (x, y, width, height) { - - return this.context.createRadialGradient(x0, y0, r0, x1, y1, r1); - - }, - - // drawImage - // drawSystemFocusRing (?) - - /** - * Draws an ellipse (oval) with a specified width (w) and height (h). - * @method Phaser.BitmapData.ellipse - * @param {number} x - x coordinate center point of ellipse. - * @param {number} y - y coordinate center point of ellipse. - * @param {number} w - height (horizontal diameter) of ellipse. The horizontal radius will be half of this number. - * @param {number} h - width (vertical diameter) of ellipse. The vertical radius will be half of this number. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - ellipse: function (x, y, w, h) { - - var k = 0.5522848; - var ox = (w / 2) * k; - var oy = (h / 2) * k; - var xe = x + w; - var ye = y + h; - var xm = x + w / 2; - var ym = y + h / 2; - - this.moveTo(x, ym); - this.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); - this.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); - this.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); - this.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); - - return this; - - }, - - /** - * Fills the subpaths with the current fill style. - * @method Phaser.BitmapData.fill - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - fill: function () { - - this._dirty = true; - this.context.fill(); - return this; - - }, - - /** - * Draws a filled rectangle at (x, y) position whose size is determined by width and height. - * @method Phaser.BitmapData.fillRect - * @param {number} x - The x axis of the coordinate for the rectangle starting point. - * @param {number} y - The y axis of the coordinate for the rectangle starting point. - * @param {number} width - The rectangles width. - * @param {number} height - The rectangles height. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - fillRect: function (x, y, width, height) { - - this._dirty = true; - this.context.fillRect(x, y, width, height); - return this; - - }, - - /** - * Sets the fill style. - * @method Phaser.BitmapData.fillStyle - * @param {string} color - The fill color value in CSS format: #RRGGBB or rgba(r,g,b,a) - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - fillStyle: function (color) { - - this.context.fillStyle = color; - return this; - - }, - - // fillText - - /** - * Sets the font. - * @method Phaser.BitmapData.font - * @param {DOMString} font - The font to be used for any text rendering. Default value 10px sans-serif. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - font: function (font) { - - this.context.font = font; - return this; - - }, - - /** - * Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque). - * @method Phaser.BitmapData.globalAlpha - * @param {number} alpha - Alpha value that is applied to shapes and images before they are composited onto the canvas. Default 1.0 (opaque). - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - globalAlpha: function (alpha) { - - this.context.globalAlpha = alpha; - return this; - - }, - - /** - * With globalAlpha applied this sets how shapes and images are drawn onto the existing bitmap. Possible values: source-atop, source-in, source-out, - * source-over (default), destination-atop, destination-in, destination-out, destination-over, lighter, darker, copy and xor. - * @method Phaser.BitmapData.globalCompositeOperation - * @param {DOMString} operation - The composite operation to apply. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - globalCompositeOperation: function (operation) { - - this.context.globalCompositeOperation = operation; - return this; - - }, - - /** - * Type of endings on the end of lines. Possible values: butt (default), round, square. - * @method Phaser.BitmapData.lineCap - * @param {DOMString} style - Possible values: butt (default), round, square - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - lineCap: function (style) { - - this.context.lineCap = style; - return this; - - }, - - /** - * Specifies where to start a dasharray on a line. - * @method Phaser.BitmapData.lineDashOffset - * @param {number} offset - Specifies where to start a dasharray on a line. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - lineDashOffset: function (offset) { - - this.context.lineDashOffset = offset; - return this; - - }, - - /** - * Defines the type of corners where two lines meet. Possible values: round, bevel, miter (default) - * @method Phaser.BitmapData.lineJoin - * @param {DOMString} join - Possible values: round, bevel, miter (default) - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - lineJoin: function (join) { - - this.context.lineJoin = join; - return this; - - }, - - /** - * Width of lines. Default 1.0 - * @method Phaser.BitmapData.lineWidth - * @param {number} width - Width of lines. Default 1.0 - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - lineWidth: function (width) { - - this.context.lineWidth = width; - return this; - - }, - - /** - * Default 10. - * @method Phaser.BitmapData.miterLimit - * @param {number} limit - Default 10. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - miterLimit: function (limit) { - - this.context.miterLimit = limit; - return this; - - }, - - // getImageData - // getLineDash - // isPointInPath - // isPointInStroke - - /** - * Connects the last point in the subpath to the x, y coordinates with a straight line. - * @method Phaser.BitmapData.lineTo - * @param {number} x - The x axis of the coordinate for the end of the line. - * @param {number} y - The y axis of the coordinate for the end of the line. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - lineTo: function (x, y) { - - this._dirty = true; - this.context.lineTo(x, y); - return this; - - }, - - // measureText - - /** - * Moves the starting point of a new subpath to the (x, y) coordinates. - * @method Phaser.BitmapData.moveTo - * @param {number} x - The x axis of the point. - * @param {number} y - The y axis of the point. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - moveTo: function (x, y) { - - this.context.moveTo(x, y); - return this; - - }, - - // putImageData - - /** - * Draws a quadratic curve from the current drawing point to (x, y) using the control point (cpx, cpy). - * @method Phaser.BitmapData.quadraticCurveTo - * @param {Number} cpx - The x axis of the control point. - * @param {Number} cpy - The y axis of the control point. - * @param {Number} x - The x axis of the ending point. - * @param {Number} y - The y axis of the ending point. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - quadraticCurveTo: function(cpx, cpy, x, y) { - - this._dirty = true; - this.context.quadraticCurveTo(cpx, cpy, x, y); - return this; - - }, - - /** - * Draws a rectangle at (x, y) position whose size is determined by width and height. - * @method Phaser.BitmapData.rect - * @param {number} x - The x axis of the coordinate for the rectangle starting point. - * @param {number} y - The y axis of the coordinate for the rectangle starting point. - * @param {number} width - The rectangles width. - * @param {number} height - The rectangles height. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - rect: function (x, y, width, height) { - - this._dirty = true; - this.context.rect(x, y, width, height); - return this; - - }, - - /** - * Restores the drawing style state to the last element on the 'state stack' saved by save(). - * @method Phaser.BitmapData.restore - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - restore: function () { - - this._dirty = true; - this.context.restore(); - return this; - - }, - - /** - * Rotates the drawing context values by r radians. - * @method Phaser.BitmapData.rotate - * @param {number} angle - The angle of rotation given in radians. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - rotate: function (angle) { - - this._dirty = true; - this.context.rotate(angle); - return this; - - }, - - /** - * Sets the stroke style for the current sub-path. Like all drawing methods, this can be chained, so you can define - * the stroke style and color in a single line of code like so: - * - * ```myGraphics.setStrokeStyle(8,"round").beginStroke("#F00");``` - * - * @method Phaser.BitmapData.setStrokeStyle - * @param {number} thickness - The width of the stroke. - * @param {string|number} [caps=0] - Indicates the type of caps to use at the end of lines. One of butt, round, or square. Defaults to "butt". Also accepts the values 0 (butt), 1 (round), and 2 (square) for use with he tiny API. - * @param {string|number} [joints=0] Specifies the type of joints that should be used where two lines meet. One of bevel, round, or miter. Defaults to "miter". Also accepts the values 0 (miter), 1 (round), and 2 (bevel) for use with the tiny API. - * @param {number} [miterLimit=10] - If joints is set to "miter", then you can specify a miter limit ratio which controls at what point a mitered joint will be clipped. - * @param {boolean} [ignoreScale=false] - If true, the stroke will be drawn at the specified thickness regardless of active transformations. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - setStrokeStyle: function (thickness, caps, joints, miterLimit, ignoreScale) { - - if (typeof thickness === 'undefined') { thickness = 1; } - if (typeof caps === 'undefined') { caps = 'butt'; } - if (typeof joints === 'undefined') { joints = 'miter'; } - if (typeof miterLimit === 'undefined') { miterLimit = 10; } - - this.lineWidth(thickness); - this.lineCap(caps); - this.lineJoin(joints); - this.miterLimit(miterLimit); - - return this; - - }, - - /** - * Saves the current drawing style state using a stack so you can revert any change you make to it using restore(). - * @method Phaser.BitmapData.save - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - save: function () { - - this._dirty = true; - this.context.save(); - return this; - - }, - - /** - * Scales the current drawing context. - * @method Phaser.BitmapData.scale - * @param {number} x - * @param {number} y - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - scale: function (x, y) { - - this._dirty = true; - this.context.scale(x, y); - return this; - - }, - - /** - * - * @method Phaser.BitmapData.scrollPathIntoView - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - scrollPathIntoView: function () { - - this._dirty = true; - this.context.scrollPathIntoView(); - return this; - - }, - - // setLineDash - // setTransform - - /** - * Strokes the subpaths with the current stroke style. - * @method Phaser.BitmapData.stroke - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - stroke: function () { - - this._dirty = true; - this.context.stroke(); - return this; - - }, - - /** - * Paints a rectangle which has a starting point at (x, y) and has a w width and an h height onto the canvas, using the current stroke style. - * @method Phaser.BitmapData.strokeRect - * @param {number} x - The x axis for the starting point of the rectangle. - * @param {number} y - The y axis for the starting point of the rectangle. - * @param {number} width - The rectangles width. - * @param {number} height - The rectangles height. - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - strokeRect: function () { - - this._dirty = true; - this.context.strokeRect(x, y, width, height); - return this; - - }, - - /** - * Color or style to use for the lines around shapes. Default #000 (black). - * @method Phaser.BitmapData.strokeStyle - * @param {string} style - Color or style to use for the lines around shapes. Default #000 (black). - * @return {Phaser.BitmapData} The BitmapData instance this method was called on. - */ - strokeStyle: function (style) { - - this.context.strokeStyle = style; - return this; - - }, - - // strokeText - // transform - // translate - - /** - * If the game is running in WebGL this will push the texture up to the GPU if it's dirty. - * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function. - * @method Phaser.BitmapData.render - */ - render: function () { - - if (this._dirty) - { - // Only needed if running in WebGL, otherwise this array will never get cleared down - if (this.game.renderType == Phaser.WEBGL) - { - PIXI.texturesToUpdate.push(this.baseTexture); - } - - this._dirty = false; - } - - } - -} - -// EaselJS Tiny API emulation - -/** -* Shortcut to moveTo. -* @method Phaser.BitmapData.prototype.mt -*/ -Phaser.BitmapData.prototype.mt = Phaser.BitmapData.prototype.moveTo; - -/** -* Shortcut to lineTo. -* @method Phaser.BitmapData.prototype.mt -*/ -Phaser.BitmapData.prototype.lt = Phaser.BitmapData.prototype.lineTo; - -/** -* Shortcut to arcTo. -* @method Phaser.BitmapData.prototype.at -*/ -Phaser.BitmapData.prototype.at = Phaser.BitmapData.prototype.arcTo; - -/** -* Shortcut to bezierCurveTo. -* @method Phaser.BitmapData.prototype.bt -*/ -Phaser.BitmapData.prototype.bt = Phaser.BitmapData.prototype.bezierCurveTo; - -/** -* Shortcut to quadraticCurveTo. -* @method Phaser.BitmapData.prototype.qt -*/ -Phaser.BitmapData.prototype.qt = Phaser.BitmapData.prototype.quadraticCurveTo; - -/** -* Shortcut to arc. -* @method Phaser.BitmapData.prototype.a -*/ -Phaser.BitmapData.prototype.a = Phaser.BitmapData.prototype.arc; - -/** -* Shortcut to rect. -* @method Phaser.BitmapData.prototype.r -*/ -Phaser.BitmapData.prototype.r = Phaser.BitmapData.prototype.rect; - -/** -* Shortcut to closePath. -* @method Phaser.BitmapData.prototype.cp -*/ -Phaser.BitmapData.prototype.cp = Phaser.BitmapData.prototype.closePath; - -/** -* Shortcut to clear. -* @method Phaser.BitmapData.prototype.c -*/ -Phaser.BitmapData.prototype.c = Phaser.BitmapData.prototype.clear; - -/** -* Shortcut to beginFill. -* @method Phaser.BitmapData.prototype.f -*/ -Phaser.BitmapData.prototype.f = Phaser.BitmapData.prototype.beginFill; - -/** -* Shortcut to beginLinearGradientFill. -* @method Phaser.BitmapData.prototype.lf -*/ -Phaser.BitmapData.prototype.lf = Phaser.BitmapData.prototype.beginLinearGradientFill; - -/** -* Shortcut to beginRadialGradientFill. -* @method Phaser.BitmapData.prototype.rf -*/ -Phaser.BitmapData.prototype.rf = Phaser.BitmapData.prototype.beginRadialGradientFill; - -/** -* Shortcut to beginBitmapFill. -* @method Phaser.BitmapData.prototype.bf -*/ -//Phaser.BitmapData.prototype.bf = Phaser.BitmapData.prototype.beginBitmapFill; - -/** -* Shortcut to endFill. -* @method Phaser.BitmapData.prototype.ef -*/ -Phaser.BitmapData.prototype.ef = Phaser.BitmapData.prototype.endFill; - -/** -* Shortcut to setStrokeStyle. -* @method Phaser.BitmapData.prototype.ss -*/ -Phaser.BitmapData.prototype.ss = Phaser.BitmapData.prototype.setStrokeStyle; - -/** -* Shortcut to beginStroke. -* @method Phaser.BitmapData.prototype.s -*/ -Phaser.BitmapData.prototype.s = Phaser.BitmapData.prototype.beginStroke; - -/** -* Shortcut to beginLinearGradientStroke. -* @method Phaser.BitmapData.prototype.ls -*/ -Phaser.BitmapData.prototype.ls = Phaser.BitmapData.prototype.beginLinearGradientStroke; - -/** -* Shortcut to beginRadialGradientStroke. -* @method Phaser.BitmapData.prototype.rs -*/ -Phaser.BitmapData.prototype.rs = Phaser.BitmapData.prototype.beginRadialGradientStroke; - -/** -* Shortcut to beginBitmapStroke. -* @method Phaser.BitmapData.prototype.bs -*/ -// Phaser.BitmapData.prototype.bs = Phaser.BitmapData.prototype.beginBitmapStroke; - -/** -* Shortcut to endStroke. -* @method Phaser.BitmapData.prototype.es -*/ -// Phaser.BitmapData.prototype.es = Phaser.BitmapData.prototype.endStroke; - -/** -* Shortcut to rect. -* @method Phaser.BitmapData.prototype.dr -*/ -Phaser.BitmapData.prototype.dr = Phaser.BitmapData.prototype.rect; - -/** -* Shortcut to drawRoundRect. -* @method Phaser.BitmapData.prototype.rr -*/ -// Phaser.BitmapData.prototype.rr = Phaser.BitmapData.prototype.drawRoundRect; - -/** -* Shortcut to drawRoundRectComplex. -* @method Phaser.BitmapData.prototype.rc -*/ -// Phaser.BitmapData.prototype.rc = Phaser.BitmapData.prototype.drawRoundRectComplex; - -/** -* Shortcut to drawCircle. -* @method Phaser.BitmapData.prototype.dc -*/ -Phaser.BitmapData.prototype.dc = Phaser.BitmapData.prototype.circle; - -/** -* Shortcut to drawEllipse. -* @method Phaser.BitmapData.prototype.de -*/ -Phaser.BitmapData.prototype.de = Phaser.BitmapData.prototype.ellipse; - -/** -* Shortcut to drawPolyStar. -* @method Phaser.BitmapData.prototype.dp -*/ -// Phaser.BitmapData.prototype.dp = Phaser.BitmapData.prototype.drawPolyStar; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Create a new `Sprite` object. Sprites are the lifeblood of your game, used for nearly everything visual. -* At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas. -* They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input), -* events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases. -* -* @class Phaser.Sprite -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - The x coordinate (in world space) to position the Sprite at. -* @param {number} y - The y coordinate (in world space) to position the Sprite at. -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. -* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -*/ -Phaser.Sprite = function (game, x, y, key, frame) { - - x = x || 0; - y = y || 0; - key = key || null; - frame = frame || null; - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all. - * @default - */ - this.exists = true; - - /** - * @property {boolean} alive - This is a handy little var your game can use to determine if a sprite is alive or not, it doesn't effect rendering. - * @default - */ - this.alive = true; - - /** - * @property {Phaser.Group} group - The parent Group of this Sprite. This is usually set after Sprite instantiation by the parent. - */ - this.group = null; - - /** - * @property {string} name - The user defined name given to this Sprite. - * @default - */ - this.name = ''; - - /** - * @property {number} type - The const type of this object. - * @default - */ - this.type = Phaser.SPRITE; - - /** - * @property {number} renderOrderID - Used by the Renderer and Input Manager to control picking order. - * @default - */ - this.renderOrderID = -1; - - /** - * If you would like the Sprite to have a lifespan once 'born' you can set this to a positive value. Handy for particles, bullets, etc. - * The lifespan is decremented by game.time.elapsed each update, once it reaches zero the kill() function is called. - * @property {number} lifespan - The lifespan of the Sprite (in ms) before it will be killed. - * @default - */ - this.lifespan = 0; - - /** - * @property {Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components. - */ - this.events = new Phaser.Events(this); - - /** - * @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager) - */ - this.animations = new Phaser.AnimationManager(this); - - /** - * @property {InputHandler} input - The Input Handler Component. - */ - this.input = new Phaser.InputHandler(this); - - /** - * @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. - */ - this.key = key; - - /** - * @property {Phaser.Frame} currentFrame - A reference to the currently displayed frame. - */ - this.currentFrame = null; - - if (key instanceof Phaser.RenderTexture) - { - PIXI.Sprite.call(this, key); - - this.currentFrame = this.game.cache.getTextureFrame(key.name); - } - else if (key instanceof Phaser.BitmapData) - { - PIXI.Sprite.call(this, key.texture, key.textureFrame); - - this.currentFrame = key.textureFrame; - } - else if (key instanceof PIXI.Texture) - { - PIXI.Sprite.call(this, key); - - this.currentFrame = frame; - } - else - { - if (key === null || typeof key === 'undefined') - { - key = '__default'; - this.key = key; - } - else if (typeof key === 'string' && this.game.cache.checkImageKey(key) == false) - { - key = '__missing'; - this.key = key; - } - - PIXI.Sprite.call(this, PIXI.TextureCache[key]); - - if (this.game.cache.isSpriteSheet(key)) - { - this.animations.loadFrameData(this.game.cache.getFrameData(key)); - - if (frame !== null) - { - if (typeof frame === 'string') - { - this.frameName = frame; - } - else - { - this.frame = frame; - } - } - } - else - { - this.currentFrame = this.game.cache.getFrame(key); - } - } - - /** - * The rectangular area from the texture that will be rendered. - * @property {Phaser.Rectangle} textureRegion - */ - this.textureRegion = new Phaser.Rectangle(this.texture.frame.x, this.texture.frame.y, this.texture.frame.width, this.texture.frame.height); - - /** - * The anchor sets the origin point of the texture. - * The default is 0,0 this means the textures origin is the top left - * Setting than anchor to 0.5,0.5 means the textures origin is centered - * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right - * - * @property {Phaser.Point} anchor - The anchor around with Sprite rotation and scaling takes place. - */ - this.anchor = new Phaser.Point(); - - /** - * @property {number} x - The x coordinate (in world space) of this Sprite. - */ - this.x = x; - - /** - * @property {number} y - The y coordinate (in world space) of this Sprite. - */ - this.y = y; - - this.position.x = x; - this.position.y = y; - - /** - * @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container. - */ - this.world = new Phaser.Point(x, y); - - /** - * Should this Sprite be automatically culled if out of range of the camera? - * A culled sprite has its renderable property set to 'false'. - * - * @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not. - * @default - */ - this.autoCull = false; - - /** - * @property {Phaser.Point} scale - The scale of the Sprite when rendered. By default it's set to 1 (no scale). You can modify it via scale.x or scale.y or scale.setTo(x, y). A value of 1 means no change to the scale, 0.5 means "half the size", 2 means "twice the size", etc. - */ - this.scale = new Phaser.Point(1, 1); - - /** - * @property {Phaser.Point} _cache - A mini cache for storing all of the calculated values. - * @private - */ - this._cache = { - - dirty: false, - - // Transform cache - a00: -1, a01: -1, a02: -1, a10: -1, a11: -1, a12: -1, id: -1, - - // Input specific transform cache - i01: -1, i10: -1, idi: -1, - - // Bounds check - left: null, right: null, top: null, bottom: null, - - // delta cache - prevX: x, prevY: y, - - // The previous calculated position - x: -1, y: -1, - - // The actual scale values based on the worldTransform - scaleX: 1, scaleY: 1, - - // The width/height of the image, based on the un-modified frame size multiplied by the final calculated scale size - width: this.currentFrame.sourceSizeW, height: this.currentFrame.sourceSizeH, - - // The actual width/height of the image if from a trimmed atlas, multiplied by the final calculated scale size - halfWidth: Math.floor(this.currentFrame.sourceSizeW / 2), halfHeight: Math.floor(this.currentFrame.sourceSizeH / 2), - - // The width/height of the image, based on the un-modified frame size multiplied by the final calculated scale size - calcWidth: -1, calcHeight: -1, - - // The current frame details - // frameID: this.currentFrame.uuid, frameWidth: this.currentFrame.width, frameHeight: this.currentFrame.height, - frameID: -1, frameWidth: this.currentFrame.width, frameHeight: this.currentFrame.height, - - // If this sprite visible to the camera (regardless of being set to visible or not) - cameraVisible: true, - - // Crop cache - cropX: 0, cropY: 0, cropWidth: this.currentFrame.sourceSizeW, cropHeight: this.currentFrame.sourceSizeH - - }; - - /** - * @property {Phaser.Point} offset - Corner point defaults. Should not typically be modified. - */ - this.offset = new Phaser.Point; - - /** - * @property {Phaser.Point} center - A Point containing the center coordinate of the Sprite. Takes rotation and scale into account. - */ - this.center = new Phaser.Point(x + Math.floor(this._cache.width / 2), y + Math.floor(this._cache.height / 2)); - - /** - * @property {Phaser.Point} topLeft - A Point containing the top left coordinate of the Sprite. Takes rotation and scale into account. - */ - this.topLeft = new Phaser.Point(x, y); - - /** - * @property {Phaser.Point} topRight - A Point containing the top right coordinate of the Sprite. Takes rotation and scale into account. - */ - this.topRight = new Phaser.Point(x + this._cache.width, y); - - /** - * @property {Phaser.Point} bottomRight - A Point containing the bottom right coordinate of the Sprite. Takes rotation and scale into account. - */ - this.bottomRight = new Phaser.Point(x + this._cache.width, y + this._cache.height); - - /** - * @property {Phaser.Point} bottomLeft - A Point containing the bottom left coordinate of the Sprite. Takes rotation and scale into account. - */ - this.bottomLeft = new Phaser.Point(x, y + this._cache.height); - - /** - * This Rectangle object fully encompasses the Sprite and is updated in real-time. - * The bounds is the full bounding area after rotation and scale have been taken into account. It should not be modified directly. - * It's used for Camera culling and physics body alignment. - * @property {Phaser.Rectangle} bounds - */ - this.bounds = new Phaser.Rectangle(x, y, this._cache.width, this._cache.height); - - /** - * @property {Phaser.Physics.Arcade.Body} body - By default Sprites have a Phaser.Physics Body attached to them. You can operate physics actions via this property, or null it to skip all physics updates. - */ - this.body = new Phaser.Physics.Arcade.Body(this); - - /** - * @property {number} health - Health value. Used in combination with damage() to allow for quick killing of Sprites. - */ - this.health = 1; - - /** - * @property {boolean} inWorld - This value is set to true if the Sprite is positioned within the World, otherwise false. - */ - this.inWorld = Phaser.Rectangle.intersects(this.bounds, this.game.world.bounds); - - /** - * @property {number} inWorldThreshold - A threshold value applied to the inWorld check. If you don't want a Sprite to be considered "out of the world" until at least 100px away for example then set it to 100. - * @default - */ - this.inWorldThreshold = 0; - - /** - * @property {boolean} outOfBoundsKill - If true the Sprite is killed as soon as Sprite.inWorld is false. - * @default - */ - this.outOfBoundsKill = false; - - /** - * @property {boolean} _outOfBoundsFired - Internal flag. - * @private - * @default - */ - this._outOfBoundsFired = false; - - /** - * A Sprite that is fixed to the camera ignores the position of any ancestors in the display list and uses its x/y coordinates as offsets from the top left of the camera. - * @property {boolean} fixedToCamera - Fixes this Sprite to the Camera. - * @default - */ - this.fixedToCamera = false; - - /** - * @property {Phaser.Point} cameraOffset - If this Sprite is fixed to the camera then use this Point to specify how far away from the Camera x/y it's rendered. - */ - this.cameraOffset = new Phaser.Point; - - /** - * You can crop the Sprites texture by modifying the crop properties. For example crop.width = 50 would set the Sprite to only render 50px wide. - * The crop is only applied if you have set Sprite.cropEnabled to true. - * @property {Phaser.Rectangle} crop - The crop Rectangle applied to the Sprite texture before rendering. - * @default - */ - this.crop = new Phaser.Rectangle(0, 0, this._cache.width, this._cache.height); - - /** - * @property {boolean} cropEnabled - If true the Sprite.crop property is used to crop the texture before render. Set to false to disable. - * @default - */ - this.cropEnabled = false; - - this.updateCache(); - this.updateBounds(); - -}; - -// Needed to keep the PIXI.Sprite constructor in the prototype chain (as the core pixi renderer uses an instanceof check sadly) -Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype); -Phaser.Sprite.prototype.constructor = Phaser.Sprite; - -/** -* Automatically called by World.preUpdate. Handles cache updates, lifespan checks, animation updates and physics updates. -* -* @method Phaser.Sprite#preUpdate -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.preUpdate = function() { - - if (!this.exists || (this.group && !this.group.exists)) - { - this.renderOrderID = -1; - - // Skip children if not exists - return false; - } - - if (this.lifespan > 0) - { - this.lifespan -= this.game.time.elapsed; - - if (this.lifespan <= 0) - { - this.kill(); - return false; - } - } - - this._cache.dirty = false; - - if (this.visible) - { - this.renderOrderID = this.game.world.currentRenderOrderID++; - } - - this.updateCache(); - - this.updateAnimation(); - - this.updateCrop(); - - // Re-run the camera visibility check - if (this._cache.dirty || this.world.x !== this._cache.prevX || this.world.y !== this._cache.prevY) - { - this.updateBounds(); - } - - if (this.body) - { - this.body.preUpdate(); - } - - return true; - -}; - -/** -* Internal function called by preUpdate. -* -* @method Phaser.Sprite#updateCache -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.updateCache = function() { - - this._cache.prevX = this.world.x; - this._cache.prevY = this.world.y; - - if (this.fixedToCamera) - { - this.x = this.game.camera.view.x + this.cameraOffset.x; - this.y = this.game.camera.view.y + this.cameraOffset.y; - } - - this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]); - - if (this.worldTransform[1] != this._cache.i01 || this.worldTransform[3] != this._cache.i10 || this.worldTransform[0] != this._cache.a00 || this.worldTransform[41] != this._cache.a11) - { - this._cache.a00 = this.worldTransform[0]; // scaleX a |a c tx| - this._cache.a01 = this.worldTransform[1]; // skewY c |b d ty| - this._cache.a10 = this.worldTransform[3]; // skewX b |0 0 1| - this._cache.a11 = this.worldTransform[4]; // scaleY d - - this._cache.i01 = this.worldTransform[1]; // skewY c (remains non-modified for input checks) - this._cache.i10 = this.worldTransform[3]; // skewX b (remains non-modified for input checks) - - this._cache.scaleX = Math.sqrt((this._cache.a00 * this._cache.a00) + (this._cache.a01 * this._cache.a01)); // round this off a bit? - this._cache.scaleY = Math.sqrt((this._cache.a10 * this._cache.a10) + (this._cache.a11 * this._cache.a11)); // round this off a bit? - - this._cache.a01 *= -1; - this._cache.a10 *= -1; - - this._cache.id = 1 / (this._cache.a00 * this._cache.a11 + this._cache.a01 * -this._cache.a10); - this._cache.idi = 1 / (this._cache.a00 * this._cache.a11 + this._cache.i01 * -this._cache.i10); - - this._cache.dirty = true; - } - - this._cache.a02 = this.worldTransform[2]; // translateX tx - this._cache.a12 = this.worldTransform[5]; // translateY ty - -}; - -/** -* Internal function called by preUpdate. -* -* @method Phaser.Sprite#updateAnimation -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.updateAnimation = function() { - - if (this.animations.update() || (this.currentFrame && this.currentFrame.uuid != this._cache.frameID)) - { - this._cache.frameID = this.currentFrame.uuid; - - this._cache.frameWidth = this.texture.frame.width; - this._cache.frameHeight = this.texture.frame.height; - - this._cache.width = this.currentFrame.width; - this._cache.height = this.currentFrame.height; - - this._cache.halfWidth = Math.floor(this._cache.width / 2); - this._cache.halfHeight = Math.floor(this._cache.height / 2); - - this._cache.dirty = true; - - } - -}; - -/** -* Internal function called by preUpdate. -* -* @method Phaser.Sprite#updateCrop -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.updateCrop = function() { - - // This only runs if crop is enabled - if (this.cropEnabled && (this.crop.width != this._cache.cropWidth || this.crop.height != this._cache.cropHeight || this.crop.x != this._cache.cropX || this.crop.y != this._cache.cropY)) - { - this.crop.floorAll(); - - this._cache.cropX = this.crop.x; - this._cache.cropY = this.crop.y; - this._cache.cropWidth = this.crop.width; - this._cache.cropHeight = this.crop.height; - - this.texture.frame = this.crop; - this.texture.width = this.crop.width; - this.texture.height = this.crop.height; - - this.texture.updateFrame = true; - - PIXI.Texture.frameUpdates.push(this.texture); - } - -}; - -/** -* Internal function called by preUpdate. -* -* @method Phaser.Sprite#updateBounds -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.updateBounds = function() { - - this.offset.setTo(this._cache.a02 - (this.anchor.x * this.width), this._cache.a12 - (this.anchor.y * this.height)); - - this.getLocalPosition(this.center, this.offset.x + (this.width / 2), this.offset.y + (this.height / 2)); - this.getLocalPosition(this.topLeft, this.offset.x, this.offset.y); - this.getLocalPosition(this.topRight, this.offset.x + this.width, this.offset.y); - this.getLocalPosition(this.bottomLeft, this.offset.x, this.offset.y + this.height); - this.getLocalPosition(this.bottomRight, this.offset.x + this.width, this.offset.y + this.height); - - this._cache.left = Phaser.Math.min(this.topLeft.x, this.topRight.x, this.bottomLeft.x, this.bottomRight.x); - this._cache.right = Phaser.Math.max(this.topLeft.x, this.topRight.x, this.bottomLeft.x, this.bottomRight.x); - this._cache.top = Phaser.Math.min(this.topLeft.y, this.topRight.y, this.bottomLeft.y, this.bottomRight.y); - this._cache.bottom = Phaser.Math.max(this.topLeft.y, this.topRight.y, this.bottomLeft.y, this.bottomRight.y); - - this.bounds.setTo(this._cache.left, this._cache.top, this._cache.right - this._cache.left, this._cache.bottom - this._cache.top); - - this.updateFrame = true; - - if (this.inWorld == false) - { - // Sprite WAS out of the screen, is it still? - this.inWorld = Phaser.Rectangle.intersects(this.bounds, this.game.world.bounds, this.inWorldThreshold); - - if (this.inWorld) - { - // It's back again, reset the OOB check - this._outOfBoundsFired = false; - } - } - else - { - // Sprite WAS in the screen, has it now left? - this.inWorld = Phaser.Rectangle.intersects(this.bounds, this.game.world.bounds, this.inWorldThreshold); - - if (this.inWorld == false) - { - this.events.onOutOfBounds.dispatch(this); - this._outOfBoundsFired = true; - - if (this.outOfBoundsKill) - { - this.kill(); - } - } - } - - this._cache.cameraVisible = Phaser.Rectangle.intersects(this.game.world.camera.screenView, this.bounds, 0); - - if (this.autoCull) - { - // Won't get rendered but will still get its transform updated - this.renderable = this._cache.cameraVisible; - } - - // Update our physics bounds - if (this.body) - { - this.body.updateBounds(this.center.x, this.center.y, this._cache.scaleX, this._cache.scaleY); - } - -}; - -/** -* Gets the local position of a coordinate relative to the Sprite, factoring in rotation and scale. -* Mostly only used internally. -* -* @method Phaser.Sprite#getLocalPosition -* @memberof Phaser.Sprite -* @param {Phaser.Point} p - The Point object to store the results in. -* @param {number} x - x coordinate within the Sprite to translate. -* @param {number} y - x coordinate within the Sprite to translate. -* @param {number} sx - Scale factor to be applied. -* @param {number} sy - Scale factor to be applied. -* @return {Phaser.Point} The translated point. -*/ -Phaser.Sprite.prototype.getLocalPosition = function(p, x, y) { - - p.x = ((this._cache.a11 * this._cache.id * x + -this._cache.a01 * this._cache.id * y + (this._cache.a12 * this._cache.a01 - this._cache.a02 * this._cache.a11) * this._cache.id) * this.scale.x) + this._cache.a02; - p.y = ((this._cache.a00 * this._cache.id * y + -this._cache.a10 * this._cache.id * x + (-this._cache.a12 * this._cache.a00 + this._cache.a02 * this._cache.a10) * this._cache.id) * this.scale.y) + this._cache.a12; - - return p; - -}; - -/** -* Gets the local unmodified position of a coordinate relative to the Sprite, factoring in rotation and scale. -* Mostly only used internally by the Input Manager, but also useful for custom hit detection. -* -* @method Phaser.Sprite#getLocalUnmodifiedPosition -* @memberof Phaser.Sprite -* @param {Phaser.Point} p - The Point object to store the results in. -* @param {number} x - x coordinate within the Sprite to translate. -* @param {number} y - x coordinate within the Sprite to translate. -* @return {Phaser.Point} The translated point. -*/ -Phaser.Sprite.prototype.getLocalUnmodifiedPosition = function(p, gx, gy) { - - p.x = (this._cache.a11 * this._cache.idi * gx + -this._cache.i01 * this._cache.idi * gy + (this._cache.a12 * this._cache.i01 - this._cache.a02 * this._cache.a11) * this._cache.idi) + (this.anchor.x * this._cache.width); - p.y = (this._cache.a00 * this._cache.idi * gy + -this._cache.i10 * this._cache.idi * gx + (-this._cache.a12 * this._cache.a00 + this._cache.a02 * this._cache.i10) * this._cache.idi) + (this.anchor.y * this._cache.height); - - return p; - -}; - -/** -* Resets the Sprite.crop value back to the frame dimensions. -* -* @method Phaser.Sprite#resetCrop -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.resetCrop = function() { - - this.crop = new Phaser.Rectangle(0, 0, this._cache.width, this._cache.height); - this.texture.setFrame(this.crop); - this.cropEnabled = false; - -}; - -/** -* Internal function called by the World postUpdate cycle. -* -* @method Phaser.Sprite#postUpdate -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.postUpdate = function() { - - if (this.key instanceof Phaser.BitmapData && this.key._dirty) - { - this.key.render(); - } - - if (this.exists) - { - // The sprite is positioned in this call, after taking into consideration motion updates and collision - if (this.body) - { - this.body.postUpdate(); - } - - if (this.fixedToCamera) - { - this._cache.x = this.game.camera.view.x + this.cameraOffset.x; - this._cache.y = this.game.camera.view.y + this.cameraOffset.y; - } - else - { - this._cache.x = this.x; - this._cache.y = this.y; - } - - this.world.setTo(this.game.camera.x + this.worldTransform[2], this.game.camera.y + this.worldTransform[5]); - - this.position.x = this._cache.x; - this.position.y = this._cache.y; - } - -}; - -/** -* Changes the Texture the Sprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache. -* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game. -* -* @method Phaser.Sprite#loadTexture -* @memberof Phaser.Sprite -* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture. -* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -*/ -Phaser.Sprite.prototype.loadTexture = function (key, frame) { - - this.key = key; - - if (key instanceof Phaser.RenderTexture) - { - this.currentFrame = this.game.cache.getTextureFrame(key.name); - } - else if (key instanceof Phaser.BitmapData) - { - this.setTexture(key.texture); - this.currentFrame = key.textureFrame; - } - else if (key instanceof PIXI.Texture) - { - this.currentFrame = frame; - } - else - { - if (typeof key === 'undefined' || this.game.cache.checkImageKey(key) === false) - { - key = '__default'; - this.key = key; - } - - if (this.game.cache.isSpriteSheet(key)) - { - this.animations.loadFrameData(this.game.cache.getFrameData(key)); - - if (typeof frame !== 'undefined') - { - if (typeof frame === 'string') - { - this.frameName = frame; - } - else - { - this.frame = frame; - } - } - } - else - { - this.currentFrame = this.game.cache.getFrame(key); - this.setTexture(PIXI.TextureCache[key]); - } - } - -}; - -/** -* Moves the sprite so its center is located on the given x and y coordinates. -* Doesn't change the anchor point of the sprite. -* -* @method Phaser.Sprite#centerOn -* @memberof Phaser.Sprite -* @param {number} x - The x coordinate (in world space) to position the Sprite at. -* @param {number} y - The y coordinate (in world space) to position the Sprite at. -* @return (Phaser.Sprite) This instance. -*/ -Phaser.Sprite.prototype.centerOn = function(x, y) { - - this.x = x + (this.x - this.center.x); - this.y = y + (this.y - this.center.y); - return this; - -}; - -/** -* Brings a 'dead' Sprite back to life, optionally giving it the health value specified. -* A resurrected Sprite has its alive, exists and visible properties all set to true. -* It will dispatch the onRevived event, you can listen to Sprite.events.onRevived for the signal. -* -* @method Phaser.Sprite#revive -* @memberof Phaser.Sprite -* @param {number} [health=1] - The health to give the Sprite. -* @return (Phaser.Sprite) This instance. -*/ -Phaser.Sprite.prototype.revive = function(health) { - - if (typeof health === 'undefined') { health = 1; } - - this.alive = true; - this.exists = true; - this.visible = true; - this.health = health; - - if (this.events) - { - this.events.onRevived.dispatch(this); - } - - return this; - -}; - -/** -* Kills a Sprite. A killed Sprite has its alive, exists and visible properties all set to false. -* It will dispatch the onKilled event, you can listen to Sprite.events.onKilled for the signal. -* Note that killing a Sprite is a way for you to quickly recycle it in a Sprite pool, it doesn't free it up from memory. -* If you don't need this Sprite any more you should call Sprite.destroy instead. -* -* @method Phaser.Sprite#kill -* @memberof Phaser.Sprite -* @return (Phaser.Sprite) This instance. -*/ -Phaser.Sprite.prototype.kill = function() { - - this.alive = false; - this.exists = false; - this.visible = false; - - if (this.events) - { - this.events.onKilled.dispatch(this); - } - - return this; - -}; - -/** -* Destroys the Sprite. This removes it from its parent group, destroys the input, event and animation handlers if present -* and nulls its reference to game, freeing it up for garbage collection. -* -* @method Phaser.Sprite#destroy -* @memberof Phaser.Sprite -*/ -Phaser.Sprite.prototype.destroy = function() { - - if (this.group) - { - this.group.remove(this); - } - - if (this.input) - { - this.input.destroy(); - } - - if (this.events) - { - this.events.destroy(); - } - - if (this.animations) - { - this.animations.destroy(); - } - - this.alive = false; - this.exists = false; - this.visible = false; - - this.game = null; - -}; - -/** -* Damages the Sprite, this removes the given amount from the Sprites health property. -* If health is then taken below zero Sprite.kill is called. -* -* @method Phaser.Sprite#damage -* @memberof Phaser.Sprite -* @param {number} amount - The amount to subtract from the Sprite.health value. -* @return (Phaser.Sprite) This instance. -*/ -Phaser.Sprite.prototype.damage = function(amount) { - - if (this.alive) - { - this.health -= amount; - - if (this.health < 0) - { - this.kill(); - } - } - - return this; - -}; - -/** -* Resets the Sprite. This places the Sprite at the given x/y world coordinates and then -* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values. -* If the Sprite has a physics body that too is reset. -* -* @method Phaser.Sprite#reset -* @memberof Phaser.Sprite -* @param {number} x - The x coordinate (in world space) to position the Sprite at. -* @param {number} y - The y coordinate (in world space) to position the Sprite at. -* @param {number} [health=1] - The health to give the Sprite. -* @return (Phaser.Sprite) This instance. -*/ -Phaser.Sprite.prototype.reset = function(x, y, health) { - - if (typeof health === 'undefined') { health = 1; } - - this.x = x; - this.y = y; - this.position.x = this.x; - this.position.y = this.y; - this.alive = true; - this.exists = true; - this.visible = true; - this.renderable = true; - this._outOfBoundsFired = false; - - this.health = health; - - if (this.body) - { - this.body.reset(); - } - - return this; - -}; - -/** -* Brings the Sprite to the top of the display list it is a child of. Sprites that are members of a Phaser.Group are only -* bought to the top of that Group, not the entire display list. -* -* @method Phaser.Sprite#bringToTop -* @memberof Phaser.Sprite -* @return (Phaser.Sprite) This instance. -*/ -Phaser.Sprite.prototype.bringToTop = function() { - - if (this.group) - { - this.group.bringToTop(this); - } - else - { - this.game.world.bringToTop(this); - } - - return this; - -}; - -/** -* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add() -* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself. -* -* @method Phaser.Sprite#play -* @memberof Phaser.Sprite -* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". -* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. -* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. -* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. -* @return {Phaser.Animation} A reference to playing Animation instance. -*/ -Phaser.Sprite.prototype.play = function (name, frameRate, loop, killOnComplete) { - - if (this.animations) - { - return this.animations.play(name, frameRate, loop, killOnComplete); - } - -}; - -/** -* Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. -* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90. -* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. -* @name Phaser.Sprite#angle -* @property {number} angle - Gets or sets the Sprites angle of rotation in degrees. -*/ -Object.defineProperty(Phaser.Sprite.prototype, 'angle', { - - get: function() { - return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); - }, - - set: function(value) { - this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); - } - -}); - -/** -* @name Phaser.Sprite#frame -* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. -*/ -Object.defineProperty(Phaser.Sprite.prototype, "frame", { - - get: function () { - return this.animations.frame; - }, - - set: function (value) { - this.animations.frame = value; - } - -}); - -/** -* @name Phaser.Sprite#frameName -* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. -*/ -Object.defineProperty(Phaser.Sprite.prototype, "frameName", { - - get: function () { - return this.animations.frameName; - }, - - set: function (value) { - this.animations.frameName = value; - } - -}); - -/** -* @name Phaser.Sprite#inCamera -* @property {boolean} inCamera - Is this sprite visible to the camera or not? -* @readonly -*/ -Object.defineProperty(Phaser.Sprite.prototype, "inCamera", { - - get: function () { - return this._cache.cameraVisible; - } - -}); - -/** -* The width of the sprite in pixels, setting this will actually modify the scale to acheive the value desired. -* If you wish to crop the Sprite instead see the Sprite.crop value. -* -* @name Phaser.Sprite#width -* @property {number} width - The width of the Sprite in pixels. -*/ -Object.defineProperty(Phaser.Sprite.prototype, 'width', { - - get: function() { - return this.scale.x * this.currentFrame.width; - }, - - set: function(value) { - - this.scale.x = value / this.currentFrame.width; - this._cache.scaleX = value / this.currentFrame.width; - this._width = value; - - } - -}); - -/** -* The height of the sprite in pixels, setting this will actually modify the scale to acheive the value desired. -* If you wish to crop the Sprite instead see the Sprite.crop value. -* -* @name Phaser.Sprite#height -* @property {number} height - The height of the Sprite in pixels. -*/ -Object.defineProperty(Phaser.Sprite.prototype, 'height', { - - get: function() { - return this.scale.y * this.currentFrame.height; - }, - - set: function(value) { - - this.scale.y = value / this.currentFrame.height; - this._cache.scaleY = value / this.currentFrame.height; - this._height = value; - - } - -}); - -/** -* By default a Sprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is -* activated for this Sprite instance and it will then start to process click/touch events and more. -* -* @name Phaser.Sprite#inputEnabled -* @property {boolean} inputEnabled - Set to true to allow this Sprite to receive input events, otherwise false. -*/ -Object.defineProperty(Phaser.Sprite.prototype, "inputEnabled", { - - get: function () { - - return (this.input.enabled); - - }, - - set: function (value) { - - if (value) - { - if (this.input.enabled == false) - { - this.input.start(); - } - } - else - { - if (this.input.enabled) - { - this.input.stop(); - } - } - - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Create a new TileSprite. -* @class Phaser.Tilemap -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {number} x - X position of the new tileSprite. -* @param {number} y - Y position of the new tileSprite. -* @param {number} width - the width of the tilesprite. -* @param {number} height - the height of the tilesprite. -* @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture. -* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index. -*/ -Phaser.TileSprite = function (game, x, y, width, height, key, frame) { - - x = x || 0; - y = y || 0; - width = width || 256; - height = height || 256; - key = key || null; - frame = frame || null; - - Phaser.Sprite.call(this, game, x, y, key, frame); - - /** - * @property {Description} texture - Description. - */ - this.texture = PIXI.TextureCache[key]; - - PIXI.TilingSprite.call(this, this.texture, width, height); - - /** - * @property {Description} type - Description. - */ - this.type = Phaser.TILESPRITE; - - /** - * @property {Point} tileScale - The scaling of the image that is being tiled. - */ - this.tileScale = new Phaser.Point(1, 1); - - /** - * @property {Point} tilePosition - The offset position of the image that is being tiled. - */ - this.tilePosition = new Phaser.Point(0, 0); - -}; - -Phaser.TileSprite.prototype = Phaser.Utils.extend(true, PIXI.TilingSprite.prototype, Phaser.Sprite.prototype); -Phaser.TileSprite.prototype.constructor = Phaser.TileSprite; - -// Add our own custom methods - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Create a new Text. -* @class Phaser.Text -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {number} x - X position of the new text object. -* @param {number} y - Y position of the new text object. -* @param {string} text - The actual text that will be written. -* @param {object} style - The style object containing style attributes like font, font size , -*/ -Phaser.Text = function (game, x, y, text, style) { - - x = x || 0; - y = y || 0; - text = text || ''; - style = style || ''; - - // If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all - /** - * @property {boolean} exists - Description. - * @default - */ - this.exists = true; - - // This is a handy little var your game can use to determine if a sprite is alive or not, it doesn't effect rendering - /** - * @property {boolean} alive - Description. - * @default - */ - this.alive = true; - - /** - * @property {Description} group - Description. - * @default - */ - this.group = null; - - /** - * @property {string} name - Description. - * @default - */ - this.name = ''; - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - this._text = text; - this._style = style; - - PIXI.Text.call(this, text, style); - - /** - * @property {Description} type - Description. - */ - this.type = Phaser.TEXT; - - /** - * @property {Description} position - Description. - */ - this.position.x = this.x = x; - this.position.y = this.y = y; - - // Replaces the PIXI.Point with a slightly more flexible one - /** - * @property {Phaser.Point} anchor - Description. - */ - this.anchor = new Phaser.Point(); - - /** - * @property {Phaser.Point} scale - Description. - */ - this.scale = new Phaser.Point(1, 1); - - // A mini cache for storing all of the calculated values - /** - * @property {Description} _cache - Description. - * @private - */ - this._cache = { - - dirty: false, - - // Transform cache - a00: 1, a01: 0, a02: x, a10: 0, a11: 1, a12: y, id: 1, - - // The previous calculated position - x: -1, y: -1, - - // The actual scale values based on the worldTransform - scaleX: 1, scaleY: 1 - - }; - - this._cache.x = this.x; - this._cache.y = this.y; - - /** - * @property {boolean} renderable - Description. - */ - this.renderable = true; - -}; - -Phaser.Text.prototype = Object.create(PIXI.Text.prototype); -Phaser.Text.prototype.constructor = Phaser.Text; - -/** -* Automatically called by World.update. -* @method Phaser.Text.prototype.update -*/ -Phaser.Text.prototype.update = function() { - - if (!this.exists) - { - return; - } - - this._cache.dirty = false; - - this._cache.x = this.x; - this._cache.y = this.y; - - if (this.position.x != this._cache.x || this.position.y != this._cache.y) - { - this.position.x = this._cache.x; - this.position.y = this._cache.y; - this._cache.dirty = true; - } - -} - -/** -* @method Phaser.Text.prototype.destroy -*/ -Phaser.Text.prototype.destroy = function() { - - if (this.group) - { - this.group.remove(this); - } - - if (this.canvas.parentNode) - { - this.canvas.parentNode.removeChild(this.canvas); - } - else - { - this.canvas = null; - this.context = null; - } - - this.exists = false; - - this.group = null; - -} - -/** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description -*/ -Object.defineProperty(Phaser.Text.prototype, 'angle', { - - get: function() { - return Phaser.Math.radToDeg(this.rotation); - }, - - set: function(value) { - this.rotation = Phaser.Math.degToRad(value); - } - -}); - -Object.defineProperty(Phaser.Text.prototype, 'content', { - - get: function() { - return this._text; - }, - - set: function(value) { - - // Let's not update unless needed, this way we can safely update the text in a core loop without constant re-draws - if (value !== this._text) - { - this._text = value; - this.setText(value); - } - - } - -}); - -Object.defineProperty(Phaser.Text.prototype, 'font', { - - get: function() { - return this._style; - }, - - set: function(value) { - - // Let's not update unless needed, this way we can safely update the text in a core loop without constant re-draws - if (value !== this._style) - { - this._style = value; - this.setStyle(value); - } - - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new `BitmapText` object. BitmapText work by taking a texture file and an XML file that describes the font layout. -* On Windows you can use the free app BMFont: http://www.angelcode.com/products/bmfont/ -* On OS X we recommend Glyph Designer: http://www.71squared.com/en/glyphdesigner -* -* @class Phaser.BitmapText -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} x - X position of the new bitmapText object. -* @param {number} y - Y position of the new bitmapText object. -* @param {string} text - The actual text that will be written. -* @param {object} style - The style object containing style attributes like font, font size , etc. -*/ -Phaser.BitmapText = function (game, x, y, text, style) { - - x = x || 0; - y = y || 0; - - text = text || ''; - style = style || ''; - - /** - * @property {boolean} exists - If exists = false then the Sprite isn't updated by the core game loop or physics subsystem at all. - * @default - */ - this.exists = true; - - /** - * @property {boolean} alive - This is a handy little var your game can use to determine if a sprite is alive or not, it doesn't effect rendering. - * @default - */ - this.alive = true; - - /** - * @property {Description} group - Description. - * @default - */ - this.group = null; - - /** - * @property {string} name - Description. - * @default - */ - this.name = ''; - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - PIXI.BitmapText.call(this, text, style); - - /** - * @property {Description} type - Description. - */ - this.type = Phaser.BITMAPTEXT; - - /** - * @property {number} position.x - Description. - */ - this.position.x = x; - - /** - * @property {number} position.y - Description. - */ - this.position.y = y; - - // Replaces the PIXI.Point with a slightly more flexible one - /** - * @property {Phaser.Point} anchor - Description. - */ - this.anchor = new Phaser.Point(); - - /** - * @property {Phaser.Point} scale - Description. - */ - this.scale = new Phaser.Point(1, 1); - - // A mini cache for storing all of the calculated values - /** - * @property {function} _cache - Description. - * @private - */ - this._cache = { - - dirty: false, - - // Transform cache - a00: 1, a01: 0, a02: x, a10: 0, a11: 1, a12: y, id: 1, - - // The previous calculated position - x: -1, y: -1, - - // The actual scale values based on the worldTransform - scaleX: 1, scaleY: 1 - - }; - - this._cache.x = this.x; - this._cache.y = this.y; - - /** - * @property {boolean} renderable - Description. - * @private - */ - this.renderable = true; - -}; - -Phaser.BitmapText.prototype = Object.create(PIXI.BitmapText.prototype); -// Phaser.BitmapText.prototype = Phaser.Utils.extend(true, PIXI.BitmapText.prototype); -Phaser.BitmapText.prototype.constructor = Phaser.BitmapText; - -/** -* Automatically called by World.update -* @method Phaser.BitmapText.prototype.update -*/ -Phaser.BitmapText.prototype.update = function() { - - if (!this.exists) - { - return; - } - - this._cache.dirty = false; - - this._cache.x = this.x; - this._cache.y = this.y; - - if (this.position.x != this._cache.x || this.position.y != this._cache.y) - { - this.position.x = this._cache.x; - this.position.y = this._cache.y; - this._cache.dirty = true; - } - - this.pivot.x = this.anchor.x*this.width; - this.pivot.y = this.anchor.y*this.height; - -} - -/** -* @method Phaser.Text.prototype.destroy -*/ -Phaser.BitmapText.prototype.destroy = function() { - - if (this.group) - { - this.group.remove(this); - } - - if (this.canvas && this.canvas.parentNode) - { - this.canvas.parentNode.removeChild(this.canvas); - } - else - { - this.canvas = null; - this.context = null; - } - - this.exists = false; - - this.group = null; - -} - -/** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description -*/ -Object.defineProperty(Phaser.BitmapText.prototype, 'angle', { - - get: function() { - return Phaser.Math.radToDeg(this.rotation); - }, - - set: function(value) { - this.rotation = Phaser.Math.degToRad(value); - } - -}); - -/** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description -*/ -Object.defineProperty(Phaser.BitmapText.prototype, 'x', { - - get: function() { - return this.position.x; - }, - - set: function(value) { - this.position.x = value; - } - -}); - -/** -* Get -* @returns {Description} -*//** -* Set -* @param {Description} value - Description -*/ -Object.defineProperty(Phaser.BitmapText.prototype, 'y', { - - get: function() { - return this.position.y; - }, - - set: function(value) { - this.position.y = value; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically. The four states a Button responds to are: -* 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'. -* 'Out' - when the Pointer that was previously over the Button moves out of it. -* 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse. -* 'Up' - when the Pointer that was pressed down on the Button is released again. -* You can set a unique texture frame and Sound for any of these states. -* -* @class Phaser.Button -* @constructor -* -* @param {Phaser.Game} game Current game instance. -* @param {number} [x] - X position of the Button. -* @param {number} [y] - Y position of the Button. -* @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this Button. -* @param {function} [callback] - The function to call when this Button is pressed. -* @param {object} [callbackContext] - The context in which the callback will be called (usually 'this'). -* @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. -* @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. -* @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. -*/ -Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame) { - - x = x || 0; - y = y || 0; - key = key || null; - callback = callback || null; - callbackContext = callbackContext || this; - - Phaser.Sprite.call(this, game, x, y, key, outFrame); - - /** - * @property {number} type - The Phaser Object Type. - */ - this.type = Phaser.BUTTON; - - /** - * @property {string} _onOverFrameName - Internal variable. - * @private - * @default - */ - this._onOverFrameName = null; - - /** - * @property {string} _onOutFrameName - Internal variable. - * @private - * @default - */ - this._onOutFrameName = null; - - /** - * @property {string} _onDownFrameName - Internal variable. - * @private - * @default - */ - this._onDownFrameName = null; - - /** - * @property {string} _onUpFrameName - Internal variable. - * @private - * @default - */ - this._onUpFrameName = null; - - /** - * @property {number} _onOverFrameID - Internal variable. - * @private - * @default - */ - this._onOverFrameID = null; - - /** - * @property {number} _onOutFrameID - Internal variable. - * @private - * @default - */ - this._onOutFrameID = null; - - /** - * @property {number} _onDownFrameID - Internal variable. - * @private - * @default - */ - this._onDownFrameID = null; - - /** - * @property {number} _onUpFrameID - Internal variable. - * @private - * @default - */ - this._onUpFrameID = null; - - /** - * @property {Phaser.Sound} onOverSound - The Sound to be played when this Buttons Over state is activated. - * @default - */ - this.onOverSound = null; - - /** - * @property {Phaser.Sound} onOutSound - The Sound to be played when this Buttons Out state is activated. - * @default - */ - this.onOutSound = null; - - /** - * @property {Phaser.Sound} onDownSound - The Sound to be played when this Buttons Down state is activated. - * @default - */ - this.onDownSound = null; - - /** - * @property {Phaser.Sound} onUpSound - The Sound to be played when this Buttons Up state is activated. - * @default - */ - this.onUpSound = null; - - /** - * @property {string} onOverSoundMarker - The Sound Marker used in conjunction with the onOverSound. - * @default - */ - this.onOverSoundMarker = ''; - - /** - * @property {string} onOutSoundMarker - The Sound Marker used in conjunction with the onOutSound. - * @default - */ - this.onOutSoundMarker = ''; - - /** - * @property {string} onDownSoundMarker - The Sound Marker used in conjunction with the onDownSound. - * @default - */ - this.onDownSoundMarker = ''; - - /** - * @property {string} onUpSoundMarker - The Sound Marker used in conjunction with the onUpSound. - * @default - */ - this.onUpSoundMarker = ''; - - /** - * @property {Phaser.Signal} onInputOver - The Signal (or event) dispatched when this Button is in an Over state. - */ - this.onInputOver = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onInputOut - The Signal (or event) dispatched when this Button is in an Out state. - */ - this.onInputOut = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onInputDown - The Signal (or event) dispatched when this Button is in an Down state. - */ - this.onInputDown = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onInputUp - The Signal (or event) dispatched when this Button is in an Up state. - */ - this.onInputUp = new Phaser.Signal; - - /** - * @property {boolean} freezeFrames - When true the Button will cease to change texture frame on all events (over, out, up, down). - */ - this.freezeFrames = false; - - /** - * When the Button is clicked you can optionally force the state to "out". - * @property {boolean} forceOut - * @default - */ - this.forceOut = true; - - this.setFrames(overFrame, outFrame, downFrame); - - if (callback !== null) - { - this.onInputUp.add(callback, callbackContext); - } - - this.input.start(0, true); - - // Redirect the input events to here so we can handle animation updates, etc - this.events.onInputOver.add(this.onInputOverHandler, this); - this.events.onInputOut.add(this.onInputOutHandler, this); - this.events.onInputDown.add(this.onInputDownHandler, this); - this.events.onInputUp.add(this.onInputUpHandler, this); - -}; - -Phaser.Button.prototype = Object.create(Phaser.Sprite.prototype); -Phaser.Button.prototype = Phaser.Utils.extend(true, Phaser.Button.prototype, Phaser.Sprite.prototype, PIXI.Sprite.prototype); -Phaser.Button.prototype.constructor = Phaser.Button; - -/** -* Used to manually set the frames that will be used for the different states of the button -* exactly like setting them in the constructor. -* -* @method Phaser.Button.prototype.setFrames -* @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name. -* @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name. -* @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name. -*/ -Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame) { - - if (overFrame !== null) - { - if (typeof overFrame === 'string') - { - this._onOverFrameName = overFrame; - - if (this.input.pointerOver()) - { - this.frameName = overFrame; - } - } - else - { - this._onOverFrameID = overFrame; - - if (this.input.pointerOver()) - { - this.frame = overFrame; - } - } - } - - if (outFrame !== null) - { - if (typeof outFrame === 'string') - { - this._onOutFrameName = outFrame; - this._onUpFrameName = outFrame; - - if (this.input.pointerOver() == false) - { - this.frameName = outFrame; - } - } - else - { - this._onOutFrameID = outFrame; - this._onUpFrameID = outFrame; - - if (this.input.pointerOver() == false) - { - this.frame = outFrame; - } - } - } - - if (downFrame !== null) - { - if (typeof downFrame === 'string') - { - this._onDownFrameName = downFrame; - - if (this.input.pointerDown()) - { - this.frameName = downFrame; - } - } - else - { - this._onDownFrameID = downFrame; - - if (this.input.pointerDown()) - { - this.frame = downFrame; - } - } - } - -}; - -/** -* Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object. -* The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound. -* Call this function with no parameters at all to reset all sounds on this Button. -* -* @method Phaser.Button.prototype.setSounds -* @param {Phaser.Sound} [overSound] - Over Button Sound. -* @param {string} [overMarker] - Over Button Sound Marker. -* @param {Phaser.Sound} [downSound] - Down Button Sound. -* @param {string} [downMarker] - Down Button Sound Marker. -* @param {Phaser.Sound} [outSound] - Out Button Sound. -* @param {string} [outMarker] - Out Button Sound Marker. -* @param {Phaser.Sound} [upSound] - Up Button Sound. -* @param {string} [upMarker] - Up Button Sound Marker. -*/ -Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) { - - this.setOverSound(overSound, overMarker); - this.setOutSound(outSound, outMarker); - this.setUpSound(upSound, upMarker); - this.setDownSound(downSound, downMarker); - -} - -/** -* The Sound to be played when a Pointer moves over this Button. -* -* @method Phaser.Button.prototype.setOverSound -* @param {Phaser.Sound} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ -Phaser.Button.prototype.setOverSound = function (sound, marker) { - - this.onOverSound = null; - this.onOverSoundMarker = ''; - - if (sound instanceof Phaser.Sound) - { - this.onOverSound = sound; - } - - if (typeof marker === 'string') - { - this.onOverSoundMarker = marker; - } - -} - -/** -* The Sound to be played when a Pointer moves out of this Button. -* -* @method Phaser.Button.prototype.setOutSound -* @param {Phaser.Sound} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ -Phaser.Button.prototype.setOutSound = function (sound, marker) { - - this.onOutSound = null; - this.onOutSoundMarker = ''; - - if (sound instanceof Phaser.Sound) - { - this.onOutSound = sound; - } - - if (typeof marker === 'string') - { - this.onOutSoundMarker = marker; - } - -} - -/** -* The Sound to be played when a Pointer clicks on this Button. -* -* @method Phaser.Button.prototype.setUpSound -* @param {Phaser.Sound} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ -Phaser.Button.prototype.setUpSound = function (sound, marker) { - - this.onUpSound = null; - this.onUpSoundMarker = ''; - - if (sound instanceof Phaser.Sound) - { - this.onUpSound = sound; - } - - if (typeof marker === 'string') - { - this.onUpSoundMarker = marker; - } - -} - -/** -* The Sound to be played when a Pointer clicks on this Button. -* -* @method Phaser.Button.prototype.setDownSound -* @param {Phaser.Sound} sound - The Sound that will be played. -* @param {string} [marker] - A Sound Marker that will be used in the playback. -*/ -Phaser.Button.prototype.setDownSound = function (sound, marker) { - - this.onDownSound = null; - this.onDownSoundMarker = ''; - - if (sound instanceof Phaser.Sound) - { - this.onDownSound = sound; - } - - if (typeof marker === 'string') - { - this.onDownSoundMarker = marker; - } - -} - -/** -* Internal function that handles input events. -* -* @protected -* @method Phaser.Button.prototype.onInputOverHandler -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ -Phaser.Button.prototype.onInputOverHandler = function (pointer) { - - if (this.freezeFrames == false) - { - if (this._onOverFrameName != null) - { - this.frameName = this._onOverFrameName; - } - else if (this._onOverFrameID != null) - { - this.frame = this._onOverFrameID; - } - } - - if (this.onOverSound) - { - this.onOverSound.play(this.onOverSoundMarker); - } - - if (this.onInputOver) - { - this.onInputOver.dispatch(this, pointer); - } -}; - -/** -* Internal function that handles input events. -* -* @protected -* @method Phaser.Button.prototype.onInputOverHandler -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ -Phaser.Button.prototype.onInputOutHandler = function (pointer) { - - if (this.freezeFrames == false) - { - if (this._onOutFrameName != null) - { - this.frameName = this._onOutFrameName; - } - else if (this._onOutFrameID != null) - { - this.frame = this._onOutFrameID; - } - } - - if (this.onOutSound) - { - this.onOutSound.play(this.onOutSoundMarker); - } - - if (this.onInputOut) - { - this.onInputOut.dispatch(this, pointer); - } -}; - -/** -* Internal function that handles input events. -* -* @protected -* @method Phaser.Button.prototype.onInputOverHandler -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ -Phaser.Button.prototype.onInputDownHandler = function (pointer) { - - if (this.freezeFrames == false) - { - if (this._onDownFrameName != null) - { - this.frameName = this._onDownFrameName; - } - else if (this._onDownFrameID != null) - { - this.frame = this._onDownFrameID; - } - } - - if (this.onDownSound) - { - this.onDownSound.play(this.onDownSoundMarker); - } - - if (this.onInputDown) - { - this.onInputDown.dispatch(this, pointer); - } -}; - -/** -* Internal function that handles input events. -* -* @protected -* @method Phaser.Button.prototype.onInputOverHandler -* @param {Phaser.Pointer} pointer - The Pointer that activated the Button. -*/ -Phaser.Button.prototype.onInputUpHandler = function (pointer) { - - if (this.freezeFrames == false) - { - if (this._onUpFrameName != null) - { - this.frameName = this._onUpFrameName; - } - else if (this._onUpFrameID != null) - { - this.frame = this._onUpFrameID; - } - } - - if (this.onUpSound) - { - this.onUpSound.play(this.onUpSoundMarker); - } - - if (this.forceOut && this.freezeFrames == false) - { - if (this._onOutFrameName != null) - { - this.frameName = this._onOutFrameName; - } - else if (this._onOutFrameID != null) - { - this.frame = this._onOutFrameID; - } - } - - if (this.onInputUp) - { - this.onInputUp.dispatch(this, pointer); - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new Graphics object. -* -* @class Phaser.Graphics -* @constructor -* -* @param {Phaser.Game} game Current game instance. -* @param {number} x - X position of the new graphics object. -* @param {number} y - Y position of the new graphics object. -*/ -Phaser.Graphics = function (game, x, y) { - - this.game = game; - - PIXI.Graphics.call(this); - - /** - * @property {Description} type - Description. - */ - this.type = Phaser.GRAPHICS; - - this.position.x = x; - this.position.y = y; - -}; - -Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype); -Phaser.Graphics.prototype.constructor = Phaser.Graphics; - -// Add our own custom methods - -/** -* Description. -* -* @method Phaser.Sprite.prototype.destroy -*/ -Phaser.Graphics.prototype.destroy = function() { - - this.clear(); - - if (this.group) - { - this.group.remove(this); - } - - this.game = null; - -} - -/* -* Draws a {Phaser.Polygon} or a {PIXI.Polygon} filled -*/ -Phaser.Graphics.prototype.drawPolygon = function (poly) { - - graphics.moveTo(poly.points[0].x, poly.points[0].y); - - for (var i = 1; i < poly.points.length; i += 1) - { - graphics.lineTo(poly.points[i].x, poly.points[i].y); - } - - graphics.lineTo(poly.points[0].x, poly.points[0].y); - -} - -Object.defineProperty(Phaser.Graphics.prototype, 'angle', { - - get: function() { - return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation)); - }, - - set: function(value) { - this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); - } - -}); - -Object.defineProperty(Phaser.Graphics.prototype, 'x', { - - get: function() { - return this.position.x; - }, - - set: function(value) { - this.position.x = value; - } - -}); - -Object.defineProperty(Phaser.Graphics.prototype, 'y', { - - get: function() { - return this.position.y; - }, - - set: function(value) { - this.position.y = value; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A RenderTexture is a special texture that allows any displayObject to be rendered to it. -* @class Phaser.RenderTexture -* @constructor -* @param {Phaser.Game} game - Current game instance. -* @param {string} key - Asset key for the render texture. -* @param {number} width - the width of the render texture. -* @param {number} height - the height of the render texture. -*/ -Phaser.RenderTexture = function (game, key, width, height) { - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {string} name - the name of the object. - */ - this.name = key; - - PIXI.EventTarget.call(this); - - /** - * @property {number} width - the width. - */ - this.width = width || 100; - - /** - * @property {number} height - the height. - */ - this.height = height || 100; - - /** - * @property {PIXI.mat3} indetityMatrix - Matrix object. - */ - this.indetityMatrix = PIXI.mat3.create(); - - /** - * @property {PIXI.Rectangle} frame - The frame for this texture. - */ - this.frame = new PIXI.Rectangle(0, 0, this.width, this.height); - - /** - * @property {number} type - Base Phaser object type. - */ - this.type = Phaser.RENDERTEXTURE; - - this._tempPoint = { x: 0, y: 0 }; - - if (PIXI.gl) - { - this.initWebGL(); - } - else - { - this.initCanvas(); - } - -}; - -Phaser.RenderTexture.prototype = Object.create(PIXI.Texture.prototype); -Phaser.RenderTexture.prototype.constructor = PIXI.RenderTexture; - -/** -* This function will draw the display object to the texture. If the display object is a Group or has children it will -* draw all children as well. -* -* @method render -* @param {DisplayObject} displayObject - The display object to render this texture on. -* @param {Phaser.Point} [position] - Where to draw the display object. -* @param {boolean} [clear=false] - If true the texture will be cleared before the displayObject is drawn. -*/ -Phaser.RenderTexture.prototype.render = function(displayObject, position, clear) { - - if (typeof position === 'undefined') { position = false; } - if (typeof clear === 'undefined') { clear = false; } - - if (displayObject instanceof Phaser.Group) - { - displayObject = displayObject._container; - } - - if (PIXI.gl) - { - this.renderWebGL(displayObject, position, clear); - } - else - { - this.renderCanvas(displayObject, position, clear); - } - -} - -/** -* This function will draw the display object to the texture at the given x/y coordinates. -* If the display object is a Group or has children it will draw all children as well. -* -* @method renderXY -* @param {DisplayObject} displayObject - The display object to render this texture on. -* @param {number} x - The x coordinate to draw the display object at. -* @param {number} y - The y coordinate to draw the display object at. -* @param {boolean} [clear=false] - If true the texture will be cleared before the displayObject is drawn. -*/ -Phaser.RenderTexture.prototype.renderXY = function(displayObject, x, y, clear) { - - this._tempPoint.x = x; - this._tempPoint.y = y; - - this.render(displayObject, this._tempPoint, clear); - -} - -/** - * Initializes the webgl data for this texture - * - * @method initWebGL - * @private - */ -Phaser.RenderTexture.prototype.initWebGL = function() -{ - var gl = PIXI.gl; - this.glFramebuffer = gl.createFramebuffer(); - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer ); - - this.glFramebuffer.width = this.width; - this.glFramebuffer.height = this.height; - - this.baseTexture = new PIXI.BaseTexture(); - - this.baseTexture.width = this.width; - this.baseTexture.height = this.height; - - this.baseTexture._glTexture = gl.createTexture(); - gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture); - - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - - this.baseTexture.isRender = true; - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer ); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.baseTexture._glTexture, 0); - - // create a projection matrix.. - this.projection = new PIXI.Point(this.width/2 , -this.height/2); - - // set the correct render function.. - // this.render = this.renderWebGL; -} - - -Phaser.RenderTexture.prototype.resize = function(width, height) -{ - - this.width = width; - this.height = height; - - if(PIXI.gl) - { - this.projection.x = this.width/2 - this.projection.y = -this.height/2; - - var gl = PIXI.gl; - gl.bindTexture(gl.TEXTURE_2D, this.baseTexture._glTexture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, this.width, this.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - } - else - { - - this.frame.width = this.width - this.frame.height = this.height; - this.renderer.resize(this.width, this.height); - } -} - -/** - * Initializes the canvas data for this texture - * - * @method initCanvas - * @private - */ -Phaser.RenderTexture.prototype.initCanvas = function() -{ - this.renderer = new PIXI.CanvasRenderer(this.width, this.height, null, 0); - - this.baseTexture = new PIXI.BaseTexture(this.renderer.view); - this.frame = new PIXI.Rectangle(0, 0, this.width, this.height); - - // this.render = this.renderCanvas; -} - -/** - * This function will draw the display object to the texture. - * - * @method renderWebGL - * @param displayObject {DisplayObject} The display object to render this texture on - * @param clear {Boolean} If true the texture will be cleared before the displayObject is drawn - * @private - */ -Phaser.RenderTexture.prototype.renderWebGL = function(displayObject, position, clear) -{ - var gl = PIXI.gl; - - // enable the alpha color mask.. - gl.colorMask(true, true, true, true); - - gl.viewport(0, 0, this.width, this.height); - - gl.bindFramebuffer(gl.FRAMEBUFFER, this.glFramebuffer ); - - if(clear) - { - gl.clearColor(0,0,0, 0); - gl.clear(gl.COLOR_BUFFER_BIT); - } - - // THIS WILL MESS WITH HIT TESTING! - var children = displayObject.children; - - //TODO -? create a new one??? dont think so! - var originalWorldTransform = displayObject.worldTransform; - displayObject.worldTransform = PIXI.mat3.create();//sthis.indetityMatrix; - // modify to flip... - displayObject.worldTransform[4] = -1; - displayObject.worldTransform[5] = this.projection.y * -2; - - if(position) - { - displayObject.worldTransform[2] = position.x; - displayObject.worldTransform[5] -= position.y; - } - - PIXI.visibleCount++; - displayObject.vcount = PIXI.visibleCount; - - for(var i=0,j=children.length; i -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Canvas class handles everything related to the <canvas> tag as a DOM Element, like styles, offset, aspect ratio -* -* @class Phaser.Canvas -* @static -*/ -Phaser.Canvas = { - - /** - * Creates the <canvas> tag - * - * @method Phaser.Canvas.create - * @param {number} width - The desired width. - * @param {number} height - The desired height. - * @return {HTMLCanvasElement} The newly created <canvas> tag. - */ - create: function (width, height) { - - width = width || 256; - height = height || 256; - - var canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - canvas.style.display = 'block'; - - return canvas; - - }, - - /** - * Get the DOM offset values of any given element - * @method Phaser.Canvas.getOffset - * @param {HTMLElement} element - The targeted element that we want to retrieve the offset. - * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset. - * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties. - */ - getOffset: function (element, point) { - - point = point || new Phaser.Point; - - var box = element.getBoundingClientRect(); - var clientTop = element.clientTop || document.body.clientTop || 0; - var clientLeft = element.clientLeft || document.body.clientLeft || 0; - var scrollTop = window.pageYOffset || element.scrollTop || document.body.scrollTop; - var scrollLeft = window.pageXOffset || element.scrollLeft || document.body.scrollLeft; - - point.x = box.left + scrollLeft - clientLeft; - point.y = box.top + scrollTop - clientTop; - - return point; - - }, - - /** - * Returns the aspect ratio of the given canvas. - * - * @method Phaser.Canvas.getAspectRatio - * @param {HTMLCanvasElement} canvas - The canvas to get the aspect ratio from. - * @return {number} The ratio between canvas' width and height. - */ - getAspectRatio: function (canvas) { - return canvas.width / canvas.height; - }, - - /** - * Sets the background color behind the canvas. This changes the canvas style property. - * - * @method Phaser.Canvas.setBackgroundColor - * @param {HTMLCanvasElement} canvas - The canvas to set the background color on. - * @param {string} [color] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color. - * @return {HTMLCanvasElement} Returns the source canvas. - */ - setBackgroundColor: function (canvas, color) { - - color = color || 'rgb(0,0,0)'; - - canvas.style.backgroundColor = color; - - return canvas; - - }, - - /** - * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions. - * - * @method Phaser.Canvas.setTouchAction - * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. - * @param {String} [value] - The touch action to set. Defaults to 'none'. - * @return {HTMLCanvasElement} The source canvas. - */ - setTouchAction: function (canvas, value) { - - value = value || 'none'; - - canvas.style.msTouchAction = value; - canvas.style['ms-touch-action'] = value; - canvas.style['touch-action'] = value; - - return canvas; - - }, - - /** - * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions. - * - * @method Phaser.Canvas.setUserSelect - * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. - * @param {String} [value] - The touch action to set. Defaults to 'none'. - * @return {HTMLCanvasElement} The source canvas. - */ - setUserSelect: function (canvas, value) { - - value = value || 'none'; - - canvas.style['-webkit-touch-callout'] = value; - canvas.style['-webkit-user-select'] = value; - canvas.style['-khtml-user-select'] = value; - canvas.style['-moz-user-select'] = value; - canvas.style['-ms-user-select'] = value; - canvas.style['user-select'] = value; - canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)'; - - return canvas; - - }, - - /** - * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent. - * If no parent is given it will be added as a child of the document.body. - * - * @method Phaser.Canvas.addToDOM - * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on. - * @param {string|HTMLElement} parent - The DOM element to add the canvas to. Defaults to ''. - * @param {boolean} overflowHidden - If set to true it will add the overflow='hidden' style to the parent DOM element. - * @return {HTMLCanvasElement} Returns the source canvas. - */ - addToDOM: function (canvas, parent, overflowHidden) { - - var target; - - if (typeof overflowHidden === 'undefined') { overflowHidden = true; } - - if (parent) - { - // hopefully an element ID - if (typeof parent === 'string') - { - target = document.getElementById(parent); - } - // quick test for a HTMLelement - else if (typeof parent === 'object' && parent.nodeType === 1) - { - target = parent; - } - - if (overflowHidden) - { - target.style.overflow = 'hidden'; - } - } - - // fallback, covers an invalid ID and a none HTMLelement object - if(!target) - { - target = document.body; - } - - target.appendChild(canvas); - - return canvas; - - }, - - /** - * Sets the transform of the given canvas to the matrix values provided. - * - * @method Phaser.Canvas.setTransform - * @param {CanvasRenderingContext2D} context - The context to set the transform on. - * @param {number} translateX - The value to translate horizontally by. - * @param {number} translateY - The value to translate vertically by. - * @param {number} scaleX - The value to scale horizontally by. - * @param {number} scaleY - The value to scale vertically by. - * @param {number} skewX - The value to skew horizontaly by. - * @param {number} skewY - The value to skew vertically by. - * @return {CanvasRenderingContext2D} Returns the source context. - */ - setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) { - - context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY); - - return context; - - }, - - /** - * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing. - * By default browsers have image smoothing enabled, which isn't always what you visually want, especially - * when using pixel art in a game. Note that this sets the property on the context itself, so that any image - * drawn to the context will be affected. This sets the property across all current browsers but support is - * patchy on earlier browsers, especially on mobile. - * - * @method Phaser.Canvas.setSmoothingEnabled - * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on. - * @param {boolean} value - If set to true it will enable image smoothing, false will disable it. - * @return {CanvasRenderingContext2D} Returns the source context. - */ - setSmoothingEnabled: function (context, value) { - - context['imageSmoothingEnabled'] = value; - context['mozImageSmoothingEnabled'] = value; - context['oImageSmoothingEnabled'] = value; - context['webkitImageSmoothingEnabled'] = value; - context['msImageSmoothingEnabled'] = value; - - return context; - - }, - - /** - * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast on webkit'). - * Note that if this doesn't given the desired result then see the setSmoothingEnabled. - * - * @method Phaser.Canvas.setImageRenderingCrisp - * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on. - * @return {HTMLCanvasElement} Returns the source canvas. - */ - setImageRenderingCrisp: function (canvas) { - - canvas.style['image-rendering'] = 'crisp-edges'; - canvas.style['image-rendering'] = '-moz-crisp-edges'; - canvas.style['image-rendering'] = '-webkit-optimize-contrast'; - canvas.style.msInterpolationMode = 'nearest-neighbor'; - - return canvas; - - }, - - /** - * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto'). - * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method. - * - * @method Phaser.Canvas.setImageRenderingBicubic - * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on. - * @return {HTMLCanvasElement} Returns the source canvas. - */ - setImageRenderingBicubic: function (canvas) { - - canvas.style['image-rendering'] = 'auto'; - canvas.style.msInterpolationMode = 'bicubic'; - - return canvas; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* An Animation instance contains a single animation and the controls to play it. -* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. -* -* @class Phaser.StageScaleMode -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {number} width - Description. -* @param {number} height - Description. -*/ -Phaser.StageScaleMode = function (game, width, height) { - - /** - * @property {Phaser.Game} game - A reference to the currently running game. - */ - this.game = game; - - /** - * @property {number} width - Width of the stage after calculation. - */ - this.width = width; - - /** - * @property {number} height - Height of the stage after calculation. - */ - this.height = height; - - /** - * @property {number} minWidth - Minimum width the canvas should be scaled to (in pixels). - * @default - */ - this.minWidth = null; - - /** - * @property {number} maxWidth - Maximum width the canvas should be scaled to (in pixels). - * If null it will scale to whatever width the browser can handle. - * @default - */ - this.maxWidth = null; - - /** - * @property {number} minHeight - Minimum height the canvas should be scaled to (in pixels). - * @default - */ - this.minHeight = null; - - /** - * @property {number} maxHeight - Maximum height the canvas should be scaled to (in pixels). - * If null it will scale to whatever height the browser can handle. - * @default - */ - this.maxHeight = null; - - /** - * @property {number} _startHeight - Stage height when starting the game. - * @default - * @private - */ - this._startHeight = 0; - - /** - * @property {boolean} forceLandscape - If the game should be forced to use Landscape mode, this is set to true by Game.Stage - * @default - */ - this.forceLandscape = false; - - /** - * @property {boolean} forcePortrait - If the game should be forced to use Portrait mode, this is set to true by Game.Stage - * @default - */ - this.forcePortrait = false; - - /** - * @property {boolean} incorrectOrientation - If the game should be forced to use a specific orientation and the device currently isn't in that orientation this is set to true. - * @default - */ - this.incorrectOrientation = false; - - /** - * @property {boolean} pageAlignHorizontally - If you wish to align your game in the middle of the page then you can set this value to true. - * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing. - * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin. - * @default - */ - this.pageAlignHorizontally = false; - - /** - * @property {boolean} pageAlignVertically - If you wish to align your game in the middle of the page then you can set this value to true. - * It will place a re-calculated margin-left pixel value onto the canvas element which is updated on orientation/resizing. - * It doesn't care about any other DOM element that may be on the page, it literally just sets the margin. - * @default - */ - this.pageAlignVertically = false; - - /** - * @property {number} _width - Cached stage width for full screen mode. - * @default - * @private - */ - this._width = 0; - - /** - * @property {number} _height - Cached stage height for full screen mode. - * @default - * @private - */ - this._height = 0; - - /** - * @property {number} maxIterations - The maximum number of times it will try to resize the canvas to fill the browser. - * @default - */ - this.maxIterations = 5; - - - /** - * @property {PIXI.Sprite} orientationSprite - The Sprite that is optionally displayed if the browser enters an unsupported orientation. - * @default - */ - this.orientationSprite = null; - - /** - * @property {Phaser.Signal} enterLandscape - The event that is dispatched when the browser enters landscape orientation. - */ - this.enterLandscape = new Phaser.Signal(); - - /** - * @property {Phaser.Signal} enterPortrait - The event that is dispatched when the browser enters horizontal orientation. - */ - this.enterPortrait = new Phaser.Signal(); - - /** - * @property {Phaser.Signal} enterIncorrectOrientation - The event that is dispatched when the browser enters an incorrect orientation, as defined by forceOrientation. - */ - this.enterIncorrectOrientation = new Phaser.Signal(); - - /** - * @property {Phaser.Signal} leaveIncorrectOrientation - The event that is dispatched when the browser leaves an incorrect orientation, as defined by forceOrientation. - */ - this.leaveIncorrectOrientation = new Phaser.Signal(); - - if (window['orientation']) - { - this.orientation = window['orientation']; - } - else - { - if (window.outerWidth > window.outerHeight) - { - this.orientation = 90; - } - else - { - this.orientation = 0; - } - } - - /** - * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions. - */ - this.scaleFactor = new Phaser.Point(1, 1); - - /** - * @property {number} aspectRatio - Aspect ratio. - * @default - */ - this.aspectRatio = 0; - - var _this = this; - - window.addEventListener('orientationchange', function (event) { - return _this.checkOrientation(event); - }, false); - - window.addEventListener('resize', function (event) { - return _this.checkResize(event); - }, false); - - document.addEventListener('webkitfullscreenchange', function (event) { - return _this.fullScreenChange(event); - }, false); - - document.addEventListener('mozfullscreenchange', function (event) { - return _this.fullScreenChange(event); - }, false); - - document.addEventListener('fullscreenchange', function (event) { - return _this.fullScreenChange(event); - }, false); - -}; - -/** -* @constant -* @type {number} -*/ -Phaser.StageScaleMode.EXACT_FIT = 0; - -/** -* @constant -* @type {number} -*/ -Phaser.StageScaleMode.NO_SCALE = 1; - -/** -* @constant -* @type {number} -*/ -Phaser.StageScaleMode.SHOW_ALL = 2; - -Phaser.StageScaleMode.prototype = { - - /** - * Tries to enter the browser into full screen mode. - * Please note that this needs to be supported by the web browser and isn't the same thing as setting your game to fill the browser. - * @method Phaser.StageScaleMode#startFullScreen - * @param {boolean} antialias - You can toggle the anti-alias feature of the canvas before jumping in to full screen (false = retain pixel art, true = smooth art) - */ - startFullScreen: function (antialias) { - - if (this.isFullScreen) - { - return; - } - - if (typeof antialias !== 'undefined') - { - Phaser.Canvas.setSmoothingEnabled(this.game.context, antialias); - } - - var element = this.game.canvas; - - this._width = this.width; - this._height = this.height; - - console.log('startFullScreen', this._width, this._height); - - if (element['requestFullScreen']) - { - element['requestFullScreen'](); - } - else if (element['mozRequestFullScreen']) - { - element['mozRequestFullScreen'](); - } - else if (element['webkitRequestFullScreen']) - { - element['webkitRequestFullScreen'](Element.ALLOW_KEYBOARD_INPUT); - } - - }, - - /** - * Stops full screen mode if the browser is in it. - * @method Phaser.StageScaleMode#stopFullScreen - */ - stopFullScreen: function () { - - if (document['cancelFullScreen']) - { - document['cancelFullScreen'](); - } - else if (document['mozCancelFullScreen']) - { - document['mozCancelFullScreen'](); - } - else if (document['webkitCancelFullScreen']) - { - document['webkitCancelFullScreen'](); - } - - }, - - /** - * Called automatically when the browser enters of leaves full screen mode. - * @method Phaser.StageScaleMode#fullScreenChange - * @param {Event} event - The fullscreenchange event - * @protected - */ - fullScreenChange: function (event) { - - if (this.isFullScreen) - { - this.game.stage.canvas.style['width'] = '100%'; - this.game.stage.canvas.style['height'] = '100%'; - - this.setMaximum(); - - this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height); - - this.aspectRatio = this.width / this.height; - this.scaleFactor.x = this.game.width / this.width; - this.scaleFactor.y = this.game.height / this.height; - } - else - { - this.game.stage.canvas.style['width'] = this.game.width + 'px'; - this.game.stage.canvas.style['height'] = this.game.height + 'px'; - - this.width = this._width; - this.height = this._height; - - this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height); - - this.aspectRatio = this.width / this.height; - this.scaleFactor.x = this.game.width / this.width; - this.scaleFactor.y = this.game.height / this.height; - } - - }, - - /** - * If you need your game to run in only one orientation you can force that to happen. - * The optional orientationImage is displayed when the game is in the incorrect orientation. - * @method Phaser.StageScaleMode#forceOrientation - * @param {boolean} forceLandscape - true if the game should run in landscape mode only. - * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only. - * @param {string} [orientationImage=''] - The string of an image in the Phaser.Cache to display when this game is in the incorrect orientation. - */ - forceOrientation: function (forceLandscape, forcePortrait, orientationImage) { - - if (typeof forcePortrait === 'undefined') { forcePortrait = false; } - - this.forceLandscape = forceLandscape; - this.forcePortrait = forcePortrait; - - if (typeof orientationImage !== 'undefined') - { - if (orientationImage == null || this.game.cache.checkImageKey(orientationImage) == false) - { - orientationImage = '__default'; - } - - this.orientationSprite = new PIXI.Sprite(PIXI.TextureCache[orientationImage]); - this.orientationSprite.anchor.x = 0.5; - this.orientationSprite.anchor.y = 0.5; - this.orientationSprite.position.x = this.game.width / 2; - this.orientationSprite.position.y = this.game.height / 2; - - this.checkOrientationState(); - - if (this.incorrectOrientation) - { - this.orientationSprite.visible = true; - this.game.world.visible = false; - } - else - { - this.orientationSprite.visible = false; - this.game.world.visible = true; - } - - this.game.stage._stage.addChild(this.orientationSprite); - } - - }, - - /** - * Checks if the browser is in the correct orientation for your game (if forceLandscape or forcePortrait have been set) - * @method Phaser.StageScaleMode#checkOrientationState - */ - checkOrientationState: function () { - - // They are in the wrong orientation - if (this.incorrectOrientation) - { - if ((this.forceLandscape && window.innerWidth > window.innerHeight) || (this.forcePortrait && window.innerHeight > window.innerWidth)) - { - // Back to normal - this.game.paused = false; - this.incorrectOrientation = false; - this.leaveIncorrectOrientation.dispatch(); - - if (this.orientationSprite) - { - this.orientationSprite.visible = false; - this.game.world.visible = true; - } - - this.refresh(); - } - } - else - { - if ((this.forceLandscape && window.innerWidth < window.innerHeight) || (this.forcePortrait && window.innerHeight < window.innerWidth)) - { - // Show orientation screen - this.game.paused = true; - this.incorrectOrientation = true; - this.enterIncorrectOrientation.dispatch(); - - if (this.orientationSprite && this.orientationSprite.visible == false) - { - this.orientationSprite.visible = true; - this.game.world.visible = false; - } - - this.refresh(); - } - } - }, - - /** - * Handle window.orientationchange events - * @method Phaser.StageScaleMode#checkOrientation - * @param {Event} event - The orientationchange event data. - */ - checkOrientation: function (event) { - - this.orientation = window['orientation']; - - if (this.isLandscape) - { - this.enterLandscape.dispatch(this.orientation, true, false); - } - else - { - this.enterPortrait.dispatch(this.orientation, false, true); - } - - if (this.game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE) - { - this.refresh(); - } - - }, - - /** - * Handle window.resize events - * @method Phaser.StageScaleMode#checkResize - * @param {Event} event - The resize event data. - */ - checkResize: function (event) { - - if (window.outerWidth > window.outerHeight) - { - this.orientation = 90; - } - else - { - this.orientation = 0; - } - - if (this.isLandscape) - { - this.enterLandscape.dispatch(this.orientation, true, false); - } - else - { - this.enterPortrait.dispatch(this.orientation, false, true); - } - - if (this.game.stage.scaleMode !== Phaser.StageScaleMode.NO_SCALE) - { - this.refresh(); - } - - this.checkOrientationState(); - - }, - - /** - * Re-calculate scale mode and update screen size. - * @method Phaser.StageScaleMode#refresh - */ - refresh: function () { - - var _this = this; - - // We can't do anything about the status bars in iPads, web apps or desktops - if (this.game.device.iPad == false && this.game.device.webApp == false && this.game.device.desktop == false) - { - // document.documentElement['style'].minHeight = '2000px'; - // this._startHeight = window.innerHeight; - - if (this.game.device.android && this.game.device.chrome == false) - { - window.scrollTo(0, 1); - } - else - { - window.scrollTo(0, 0); - } - } - - if (this._check == null && this.maxIterations > 0) - { - this._iterations = this.maxIterations; - this._check = window.setInterval(function () { - return _this.setScreenSize(); - }, 10); - this.setScreenSize(); - } - - }, - - /** - * Set screen size automatically based on the scaleMode. - * @param {boolean} force - If force is true it will try to resize the game regardless of the document dimensions. - */ - setScreenSize: function (force) { - - if (typeof force == 'undefined') - { - force = false; - } - - if (this.game.device.iPad == false && this.game.device.webApp == false && this.game.device.desktop == false) - { - if (this.game.device.android && this.game.device.chrome == false) - { - window.scrollTo(0, 1); - } - else - { - window.scrollTo(0, 0); - } - } - - this._iterations--; - - if (force || window.innerHeight > this._startHeight || this._iterations < 0) - { - // Set minimum height of content to new window height - document.documentElement['style'].minHeight = window.innerHeight + 'px'; - - if (this.incorrectOrientation == true) - { - this.setMaximum(); - } - else if (this.game.stage.scaleMode == Phaser.StageScaleMode.EXACT_FIT) - { - this.setExactFit(); - } - else if (this.game.stage.scaleMode == Phaser.StageScaleMode.SHOW_ALL) - { - this.setShowAll(); - } - - this.setSize(); - clearInterval(this._check); - this._check = null; - } - - }, - - /** - * Sets the canvas style width and height values based on minWidth/Height and maxWidth/Height. - * @method Phaser.StageScaleMode#setSize - */ - setSize: function () { - - if (this.incorrectOrientation == false) - { - if (this.maxWidth && this.width > this.maxWidth) - { - this.width = this.maxWidth; - } - - if (this.maxHeight && this.height > this.maxHeight) - { - this.height = this.maxHeight; - } - - if (this.minWidth && this.width < this.minWidth) - { - this.width = this.minWidth; - } - - if (this.minHeight && this.height < this.minHeight) - { - this.height = this.minHeight; - } - } - - this.game.canvas.style.width = this.width + 'px'; - this.game.canvas.style.height = this.height + 'px'; - - this.game.input.scale.setTo(this.game.width / this.width, this.game.height / this.height); - - if (this.pageAlignHorizontally) - { - if (this.width < window.innerWidth && this.incorrectOrientation == false) - { - this.game.canvas.style.marginLeft = Math.round((window.innerWidth - this.width) / 2) + 'px'; - } - else - { - this.game.canvas.style.marginLeft = '0px'; - } - } - - if (this.pageAlignVertically) - { - if (this.height < window.innerHeight && this.incorrectOrientation == false) - { - this.game.canvas.style.marginTop = Math.round((window.innerHeight - this.height) / 2) + 'px'; - } - else - { - this.game.canvas.style.marginTop = '0px'; - } - } - - Phaser.Canvas.getOffset(this.game.canvas, this.game.stage.offset); - - this.aspectRatio = this.width / this.height; - - this.scaleFactor.x = this.game.width / this.width; - this.scaleFactor.y = this.game.height / this.height; - - this.checkOrientationState(); - - }, - - /** - * Sets this.width equal to window.innerWidth and this.height equal to window.innerHeight - * @method Phaser.StageScaleMode#setMaximum - */ - setMaximum: function () { - - this.width = window.innerWidth; - this.height = window.innerHeight; - - }, - - /** - * Calculates the multiplier needed to scale the game proportionally. - * @method Phaser.StageScaleMode#setShowAll - */ - setShowAll: function () { - - var multiplier = Math.min((window.innerHeight / this.game.height), (window.innerWidth / this.game.width)); - - this.width = Math.round(this.game.width * multiplier); - this.height = Math.round(this.game.height * multiplier); - - }, - - /** - * Sets the width and height values of the canvas, no larger than the maxWidth/Height. - * @method Phaser.StageScaleMode#setExactFit - */ - setExactFit: function () { - - var availableWidth = window.innerWidth; - var availableHeight = window.innerHeight; - - // console.log('available', availableWidth, availableHeight); - - if (this.maxWidth && availableWidth > this.maxWidth) - { - this.width = this.maxWidth; - } - else - { - this.width = availableWidth; - } - - if (this.maxHeight && availableHeight > this.maxHeight) - { - this.height = this.maxHeight; - } - else - { - this.height = availableHeight; - } - - } - -}; - -/** -* @name Phaser.StageScaleMode#isFullScreen -* @property {boolean} isFullScreen - Returns true if the browser is in full screen mode, otherwise false. -* @readonly -*/ -Object.defineProperty(Phaser.StageScaleMode.prototype, "isFullScreen", { - - get: function () { - - return (document['fullscreenElement'] || document['mozFullScreenElement'] || document['webkitFullscreenElement']) - - } - -}); - -/** -* @name Phaser.StageScaleMode#isPortrait -* @property {boolean} isPortrait - Returns true if the browser dimensions match a portrait display. -* @readonly -*/ -Object.defineProperty(Phaser.StageScaleMode.prototype, "isPortrait", { - - get: function () { - return this.orientation == 0 || this.orientation == 180; - } - -}); - -/** -* @name Phaser.StageScaleMode#isLandscape -* @property {boolean} isLandscape - Returns true if the browser dimensions match a landscape display. -* @readonly -*/ -Object.defineProperty(Phaser.StageScaleMode.prototype, "isLandscape", { - - get: function () { - return this.orientation === 90 || this.orientation === -90; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Detects device support capabilities. Using some elements from System.js by MrDoob and Modernizr -* -* @class Phaser.Device -* @constructor -*/ - -Phaser.Device = function () { - - /** - * An optional 'fix' for the horrendous Android stock browser bug https://code.google.com/p/android/issues/detail?id=39247 - * @property {boolean} patchAndroidClearRectBug - Description. - * @default - */ - this.patchAndroidClearRectBug = false; - - // Operating System - - /** - * @property {boolean} desktop - Is running desktop? - * @default - */ - this.desktop = false; - - /** - * @property {boolean} iOS - Is running on iOS? - * @default - */ - this.iOS = false; - - /** - * @property {boolean} android - Is running on android? - * @default - */ - this.android = false; - - /** - * @property {boolean} chromeOS - Is running on chromeOS? - * @default - */ - this.chromeOS = false; - - /** - * @property {boolean} linux - Is running on linux? - * @default - */ - this.linux = false; - - /** - * @property {boolean} macOS - Is running on macOS? - * @default - */ - this.macOS = false; - - /** - * @property {boolean} windows - Is running on windows? - * @default - */ - this.windows = false; - - // Features - - /** - * @property {boolean} canvas - Is canvas available? - * @default - */ - this.canvas = false; - - /** - * @property {boolean} file - Is file available? - * @default - */ - this.file = false; - - /** - * @property {boolean} fileSystem - Is fileSystem available? - * @default - */ - this.fileSystem = false; - - /** - * @property {boolean} localStorage - Is localStorage available? - * @default - */ - this.localStorage = false; - - /** - * @property {boolean} webGL - Is webGL available? - * @default - */ - this.webGL = false; - - /** - * @property {boolean} worker - Is worker available? - * @default - */ - this.worker = false; - - /** - * @property {boolean} touch - Is touch available? - * @default - */ - this.touch = false; - - /** - * @property {boolean} mspointer - Is mspointer available? - * @default - */ - this.mspointer = false; - - /** - * @property {boolean} css3D - Is css3D available? - * @default - */ - this.css3D = false; - - /** - * @property {boolean} pointerLock - Is Pointer Lock available? - * @default - */ - this.pointerLock = false; - - /** - * @property {boolean} typedArray - Does the browser support TypedArrays? - * @default - */ - this.typedArray = false; - - // Browser - - /** - * @property {boolean} arora - Set to true if running in Arora. - * @default - */ - this.arora = false; - - /** - * @property {boolean} chrome - Set to true if running in Chrome. - * @default - */ - this.chrome = false; - - /** - * @property {boolean} epiphany - Set to true if running in Epiphany. - * @default - */ - this.epiphany = false; - - /** - * @property {boolean} firefox - Set to true if running in Firefox. - * @default - */ - this.firefox = false; - - /** - * @property {boolean} ie - Set to true if running in Internet Explorer. - * @default - */ - this.ie = false; - - /** - * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. - * @default - */ - this.ieVersion = 0; - - /** - * @property {boolean} mobileSafari - Set to true if running in Mobile Safari. - * @default - */ - this.mobileSafari = false; - - /** - * @property {boolean} midori - Set to true if running in Midori. - * @default - */ - this.midori = false; - - /** - * @property {boolean} opera - Set to true if running in Opera. - * @default - */ - this.opera = false; - - /** - * @property {boolean} safari - Set to true if running in Safari. - * @default - */ - this.safari = false; - - /** - * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView - * @default - */ - this.webApp = false; - - // Audio - - /** - * @property {boolean} audioData - Are Audio tags available? - * @default - */ - this.audioData = false; - - /** - * @property {boolean} webAudio - Is the WebAudio API available? - * @default - */ - this.webAudio = false; - - /** - * @property {boolean} ogg - Can this device play ogg files? - * @default - */ - this.ogg = false; - - /** - * @property {boolean} opus - Can this device play opus files? - * @default - */ - this.opus = false; - - /** - * @property {boolean} mp3 - Can this device play mp3 files? - * @default - */ - this.mp3 = false; - - /** - * @property {boolean} wav - Can this device play wav files? - * @default - */ - this.wav = false; - - /** - * Can this device play m4a files? - * @property {boolean} m4a - True if this device can play m4a files. - * @default - */ - this.m4a = false; - - /** - * @property {boolean} webm - Can this device play webm files? - * @default - */ - this.webm = false; - - // Device - - /** - * @property {boolean} iPhone - Is running on iPhone? - * @default - */ - this.iPhone = false; - - /** - * @property {boolean} iPhone4 - Is running on iPhone4? - * @default - */ - this.iPhone4 = false; - - /** - * @property {boolean} iPad - Is running on iPad? - * @default - */ - this.iPad = false; - - /** - * @property {number} pixelRatio - PixelRatio of the host device? - * @default - */ - this.pixelRatio = 0; - - /** - * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays) - * @default - */ - this.littleEndian = false; - - // Run the checks - this._checkAudio(); - this._checkBrowser(); - this._checkCSS3D(); - this._checkDevice(); - this._checkFeatures(); - this._checkOS(); - -}; - -Phaser.Device.prototype = { - - /** - * Check which OS is game running on. - * @method Phaser.Device#_checkOS - * @private - */ - _checkOS: function () { - - var ua = navigator.userAgent; - - if (/Android/.test(ua)) { - this.android = true; - } else if (/CrOS/.test(ua)) { - this.chromeOS = true; - } else if (/iP[ao]d|iPhone/i.test(ua)) { - this.iOS = true; - } else if (/Linux/.test(ua)) { - this.linux = true; - } else if (/Mac OS/.test(ua)) { - this.macOS = true; - } else if (/Windows/.test(ua)) { - this.windows = true; - } - - if (this.windows || this.macOS || this.linux) { - this.desktop = true; - } - - }, - - /** - * Check HTML5 features of the host environment. - * @method Phaser.Device#_checkFeatures - * @private - */ - _checkFeatures: function () { - - this.canvas = !!window['CanvasRenderingContext2D']; - - try { - this.localStorage = !!localStorage.getItem; - } catch (error) { - this.localStorage = false; - } - - this.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob']; - this.fileSystem = !!window['requestFileSystem']; - this.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )(); - - if (this.webGL === null || this.webGL === false) - { - this.webGL = false; - } - else - { - this.webGL = true; - } - - this.worker = !!window['Worker']; - - if ('ontouchstart' in document.documentElement || window.navigator.msPointerEnabled) { - this.touch = true; - } - - if (window.navigator.msPointerEnabled) { - this.mspointer = true; - } - - this.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document; - - }, - - /** - * Check what browser is game running in. - * @method Phaser.Device#_checkBrowser - * @private - */ - _checkBrowser: function () { - - var ua = navigator.userAgent; - - if (/Arora/.test(ua)) { - this.arora = true; - } else if (/Chrome/.test(ua)) { - this.chrome = true; - } else if (/Epiphany/.test(ua)) { - this.epiphany = true; - } else if (/Firefox/.test(ua)) { - this.firefox = true; - } else if (/Mobile Safari/.test(ua)) { - this.mobileSafari = true; - } else if (/MSIE (\d+\.\d+);/.test(ua)) { - this.ie = true; - this.ieVersion = parseInt(RegExp.$1); - } else if (/Midori/.test(ua)) { - this.midori = true; - } else if (/Opera/.test(ua)) { - this.opera = true; - } else if (/Safari/.test(ua)) { - this.safari = true; - } - - // WebApp mode in iOS - if (navigator['standalone']) { - this.webApp = true; - } - - }, - - /** - * Check audio support. - * @method Phaser.Device#_checkAudio - * @private - */ - _checkAudio: function () { - - this.audioData = !!(window['Audio']); - this.webAudio = !!(window['webkitAudioContext'] || window['AudioContext']); - var audioElement = document.createElement('audio'); - var result = false; - - try { - if (result = !!audioElement.canPlayType) { - - if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) { - this.ogg = true; - } - - if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '')) { - this.opus = true; - } - - if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, '')) { - this.mp3 = true; - } - - // Mimetypes accepted: - // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements - // bit.ly/iphoneoscodecs - if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, '')) { - this.wav = true; - } - - if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, '')) { - this.m4a = true; - } - - if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, '')) { - this.webm = true; - } - } - } catch (e) { - } - - }, - - /** - * Check PixelRatio of devices. - * @method Phaser.Device#_checkDevice - * @private - */ - _checkDevice: function () { - - this.pixelRatio = window['devicePixelRatio'] || 1; - this.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') != -1; - this.iPhone4 = (this.pixelRatio == 2 && this.iPhone); - this.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') != -1; - - if (typeof Int8Array !== 'undefined') - { - this.littleEndian = new Int8Array(new Int16Array([1]).buffer)[0] > 0; - this.typedArray = true; - } - else - { - this.littleEndian = false; - this.typedArray = false; - } - - }, - - /** - * Check whether the host environment support 3D CSS. - * @method Phaser.Device#_checkCSS3D - * @private - */ - _checkCSS3D: function () { - - var el = document.createElement('p'); - var has3d; - var transforms = { - 'webkitTransform': '-webkit-transform', - 'OTransform': '-o-transform', - 'msTransform': '-ms-transform', - 'MozTransform': '-moz-transform', - 'transform': 'transform' - }; - - // Add it to the body to get the computed style. - document.body.insertBefore(el, null); - - for (var t in transforms) { - if (el.style[t] !== undefined) { - el.style[t] = "translate3d(1px,1px,1px)"; - has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); - } - } - - document.body.removeChild(el); - this.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none"); - - }, - - /** - * Check whether the host environment can play audio. - * @method Phaser.Device#canPlayAudio - * @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm'. - * @return {boolean} True if the given file type is supported by the browser, otherwise false. - */ - canPlayAudio: function (type) { - - if (type == 'mp3' && this.mp3) - { - return true; - } - else if (type == 'ogg' && (this.ogg || this.opus)) - { - return true; - } - else if (type == 'm4a' && this.m4a) - { - return true; - } - else if (type == 'wav' && this.wav) - { - return true; - } - else if (type == 'webm' && this.webm) - { - return true; - } - - return false; - - }, - - /** - * Check whether the console is open. - * @method Phaser.Device#isConsoleOpen - * @return {boolean} True if the browser dev console is open. - */ - isConsoleOpen: function () { - - if (window.console && window.console['firebug']) - { - return true; - } - - if (window.console) - { - console.profile(); - console.profileEnd(); - - if (console.clear) - { - console.clear(); - } - - return console['profiles'].length > 0; - } - - return false; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Abstracts away the use of RAF or setTimeOut for the core game update loop. -* -* @class Phaser.RequestAnimationFrame -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.RequestAnimationFrame = function(game) { - - /** - * @property {Phaser.Game} game - The currently running game. - */ - this.game = game; - - /** - * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false. - * @default - */ - this.isRunning = false; - - var vendors = [ - 'ms', - 'moz', - 'webkit', - 'o' - ]; - - for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++) - { - window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; - window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']; - } - - /** - * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf. - * @private - */ - this._isSetTimeOut = false; - - /** - * @property {function} _onLoop - The function called by the update. - * @private - */ - this._onLoop = null; - - /** - * @property {number} _timeOutID - The callback ID used when calling cancel. - * @private - */ - this._timeOutID = null; - -}; - -Phaser.RequestAnimationFrame.prototype = { - - /** - * Starts the requestAnimatioFrame running or setTimeout if unavailable in browser - * @method Phaser.RequestAnimationFrame#start - */ - start: function () { - - this.isRunning = true; - - var _this = this; - - if (!window.requestAnimationFrame) - { - this._isSetTimeOut = true; - - this._onLoop = function () { - return _this.updateSetTimeout(); - }; - - this._timeOutID = window.setTimeout(this._onLoop, 0); - } - else - { - this._isSetTimeOut = false; - - this._onLoop = function (time) { - return _this.updateRAF(time); - }; - - this._timeOutID = window.requestAnimationFrame(this._onLoop); - } - - }, - - /** - * The update method for the requestAnimationFrame - * @method Phaser.RequestAnimationFrame#updateRAF - * @param {number} time - A timestamp, either from RAF or setTimeOut - */ - updateRAF: function (time) { - - this.game.update(time); - - this._timeOutID = window.requestAnimationFrame(this._onLoop); - - }, - - /** - * The update method for the setTimeout. - * @method Phaser.RequestAnimationFrame#updateSetTimeout - */ - updateSetTimeout: function () { - - this.game.update(Date.now()); - - this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall); - - }, - - /** - * Stops the requestAnimationFrame from running. - * @method Phaser.RequestAnimationFrame#stop - */ - stop: function () { - - if (this._isSetTimeOut) - { - clearTimeout(this._timeOutID); - } - else - { - window.cancelAnimationFrame(this._timeOutID); - } - - this.isRunning = false; - - }, - - /** - * Is the browser using setTimeout? - * @method Phaser.RequestAnimationFrame#isSetTimeOut - * @return {boolean} - */ - isSetTimeOut: function () { - return this._isSetTimeOut; - }, - - /** - * Is the browser using requestAnimationFrame? - * @method Phaser.RequestAnimationFrame#isRAF - * @return {boolean} - */ - isRAF: function () { - return (this._isSetTimeOut === false); - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser.RandomDataGenerator constructor. -* -* @class Phaser.RandomDataGenerator -* @classdesc An extremely useful repeatable random data generator. Access it via Phaser.Game.rnd -* Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense. -* Random number generator from http://baagoe.org/en/wiki/Better_random_numbers_for_javascript -* -* @constructor -* @param {array} seeds -*/ -Phaser.RandomDataGenerator = function (seeds) { - - if (typeof seeds === "undefined") { seeds = []; } - - this.sow(seeds); - -}; - -Phaser.RandomDataGenerator.prototype = { - - /** - * @property {number} c - * @private - */ - c: 1, - - /** - * @property {number} s0 - * @private - */ - s0: 0, - - /** - * @property {number} s1 - * @private - */ - s1: 0, - - /** - * @property {number} s2 - * @private - */ - s2: 0, - - /** - * Private random helper. - * @method Phaser.RandomDataGenerator#rnd - * @private - * @return {number} Description. - */ - rnd: function () { - - var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32 - - this.c = t | 0; - this.s0 = this.s1; - this.s1 = this.s2; - this.s2 = t - this.c; - - return this.s2; - }, - - /** - * Reset the seed of the random data generator. - * - * @method Phaser.RandomDataGenerator#sow - * @param {array} seeds - */ - sow: function (seeds) { - - if (typeof seeds === "undefined") { seeds = []; } - - this.s0 = this.hash(' '); - this.s1 = this.hash(this.s0); - this.s2 = this.hash(this.s1); - this.c = 1; - - var seed; - - for (var i = 0; seed = seeds[i++]; ) - { - this.s0 -= this.hash(seed); - this.s0 += ~~(this.s0 < 0); - this.s1 -= this.hash(seed); - this.s1 += ~~(this.s1 < 0); - this.s2 -= this.hash(seed); - this.s2 += ~~(this.s2 < 0); - } - - }, - - /** - * Description. - * @method Phaser.RandomDataGenerator#hash - * @param {Any} data - * @private - * @return {number} Description. - */ - hash: function (data) { - - var h, i, n; - n = 0xefc8249d; - data = data.toString(); - - for (i = 0; i < data.length; i++) { - n += data.charCodeAt(i); - h = 0.02519603282416938 * n; - n = h >>> 0; - h -= n; - h *= n; - n = h >>> 0; - h -= n; - n += h * 0x100000000;// 2^32 - } - - return (n >>> 0) * 2.3283064365386963e-10;// 2^-32 - - }, - - /** - * Returns a random integer between 0 and 2^32. - * @method Phaser.RandomDataGenerator#integer - * @return {number} - */ - integer: function() { - return this.rnd.apply(this) * 0x100000000;// 2^32 - }, - - /** - * Returns a random real number between 0 and 1. - * @method Phaser.RandomDataGenerator#frac - * @return {number} - */ - frac: function() { - return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16;// 2^-53 - }, - - /** - * Returns a random real number between 0 and 2^32. - * @method Phaser.RandomDataGenerator#real - * @return {number} - */ - real: function() { - return this.integer() + this.frac(); - }, - - /** - * Returns a random integer between min and max. - * @method Phaser.RandomDataGenerator#integerInRange - * @param {number} min - * @param {number} max - * @return {number} - */ - integerInRange: function (min, max) { - return Math.floor(this.realInRange(min, max)); - }, - - /** - * Returns a random real number between min and max. - * @method Phaser.RandomDataGenerator#realInRange - * @param {number} min - * @param {number} max - * @return {number} - */ - realInRange: function (min, max) { - - return this.frac() * (max - min) + min; - - }, - - /** - * Returns a random real number between -1 and 1. - * @method Phaser.RandomDataGenerator#normal - * @return {number} - */ - normal: function () { - return 1 - 2 * this.frac(); - }, - - /** - * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368 - * @method Phaser.RandomDataGenerator#uuid - * @return {string} - */ - uuid: function () { - - var a, b; - - for ( - b=a=''; - a++<36; - b+=~a%5|a*3&4?(a^15?8^this.frac()*(a^20?16:4):4).toString(16):'-' - ); - - return b; - - }, - - /** - * Returns a random member of `array`. - * @method Phaser.RandomDataGenerator#pick - * @param {Any} ary - * @return {number} - */ - pick: function (ary) { - return ary[this.integerInRange(0, ary.length)]; - }, - - /** - * Returns a random member of `array`, favoring the earlier entries. - * @method Phaser.RandomDataGenerator#weightedPick - * @param {Any} ary - * @return {number} - */ - weightedPick: function (ary) { - return ary[~~(Math.pow(this.frac(), 2) * ary.length)]; - }, - - /** - * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified. - * @method Phaser.RandomDataGenerator#timestamp - * @param {number} min - * @param {number} max - * @return {number} - */ - timestamp: function (a, b) { - return this.realInRange(a || 946684800000, b || 1577862000000); - }, - - /** - * Returns a random angle between -180 and 180. - * @method Phaser.RandomDataGenerator#angle - * @return {number} - */ - angle: function() { - return this.integerInRange(-180, 180); - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A collection of mathematical methods. -* -* @class Phaser.Math -*/ -Phaser.Math = { - - /** - * = 2 π - * @method Phaser.Math#PI2 - */ - PI2: Math.PI * 2, - - /** - * Two number are fuzzyEqual if their difference is less than ε. - * @method Phaser.Math#fuzzyEqual - * @param {number} a - * @param {number} b - * @param {number} epsilon - * @return {boolean} True if |a-b|<ε - */ - fuzzyEqual: function (a, b, epsilon) { - if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return Math.abs(a - b) < epsilon; - }, - - /** - * a is fuzzyLessThan b if it is less than b + ε. - * @method Phaser.Math#fuzzyEqual - * @param {number} a - * @param {number} b - * @param {number} epsilon - * @return {boolean} True if ab+ε - */ - fuzzyGreaterThan: function (a, b, epsilon) { - if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return a > b - epsilon; - }, - - /** - * @method Phaser.Math#fuzzyCeil - * @param {number} val - * @param {number} epsilon - * @return {boolean} ceiling(val-ε) - */ - fuzzyCeil: function (val, epsilon) { - if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return Math.ceil(val - epsilon); - }, - - /** - * @method Phaser.Math#fuzzyFloor - * @param {number} val - * @param {number} epsilon - * @return {boolean} floor(val-ε) - */ - fuzzyFloor: function (val, epsilon) { - if (typeof epsilon === "undefined") { epsilon = 0.0001; } - return Math.floor(val + epsilon); - }, - - /** - * Averages all values passed to the function and returns the result. You can pass as many parameters as you like. - * @method Phaser.Math#average - * @return {number} The average of all given values. - */ - average: function () { - - var args = []; - - for (var _i = 0; _i < (arguments.length - 0); _i++) { - args[_i] = arguments[_i + 0]; - } - - var avg = 0; - - for (var i = 0; i < args.length; i++) { - avg += args[i]; - } - - return avg / args.length; - - }, - - /** - * @method Phaser.Math#truncate - * @param {number} n - * @return {number} - */ - truncate: function (n) { - return (n > 0) ? Math.floor(n) : Math.ceil(n); - }, - - /** - * @method Phaser.Math#shear - * @param {number} n - * @return {number} n mod 1 - */ - shear: function (n) { - return n % 1; - }, - - /** - * Snap a value to nearest grid slice, using rounding. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15. - * - * @method Phaser.Math#snapTo - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start] - Optional starting offset for gap. - * @return {number} - */ - snapTo: function (input, gap, start) { - - if (typeof start === "undefined") { start = 0; } - - if (gap == 0) { - return input; - } - - input -= start; - input = gap * Math.round(input / gap); - - return start + input; - - }, - - /** - * Snap a value to nearest grid slice, using floor. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10. As will 14 snap to 10... but 16 will snap to 15 - * - * @method Phaser.Math#snapToFloor - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start] - Optional starting offset for gap. - * @return {number} - */ - snapToFloor: function (input, gap, start) { - - if (typeof start === "undefined") { start = 0; } - - if (gap == 0) { - return input; - } - - input -= start; - input = gap * Math.floor(input / gap); - - return start + input; - - }, - - /** - * Snap a value to nearest grid slice, using ceil. - * - * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15. As will 14 will snap to 15... but 16 will snap to 20. - * - * @method Phaser.Math#snapToCeil - * @param {number} input - The value to snap. - * @param {number} gap - The interval gap of the grid. - * @param {number} [start] - Optional starting offset for gap. - * @return {number} - */ - snapToCeil: function (input, gap, start) { - - if (typeof start === "undefined") { start = 0; } - - if (gap == 0) { - return input; - } - - input -= start; - input = gap * Math.ceil(input / gap); - - return start + input; - - }, - - - /** - * Snaps a value to the nearest value in an array. - * @method Phaser.Math#snapToInArray - * @param {number} input - * @param {array} arr - * @param {boolean} sort - True if the array needs to be sorted. - * @return {number} - */ - snapToInArray: function (input, arr, sort) { - - if (typeof sort === "undefined") { sort = true; } - - if (sort) { - arr.sort(); - } - - if (input < arr[0]) { - return arr[0]; - } - - var i = 1; - - while (arr[i] < input) { - i++; - } - - var low = arr[i - 1]; - var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY; - - return ((high - input) <= (input - low)) ? high : low; - - }, - - /** - * Round to some place comparative to a 'base', default is 10 for decimal place. - * - * 'place' is represented by the power applied to 'base' to get that place - * e.g. - * 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011 - * - * roundTo(2000/7,3) == 0 - * roundTo(2000/7,2) == 300 - * roundTo(2000/7,1) == 290 - * roundTo(2000/7,0) == 286 - * roundTo(2000/7,-1) == 285.7 - * roundTo(2000/7,-2) == 285.71 - * roundTo(2000/7,-3) == 285.714 - * roundTo(2000/7,-4) == 285.7143 - * roundTo(2000/7,-5) == 285.71429 - * - * roundTo(2000/7,3,2) == 288 -- 100100000 - * roundTo(2000/7,2,2) == 284 -- 100011100 - * roundTo(2000/7,1,2) == 286 -- 100011110 - * roundTo(2000/7,0,2) == 286 -- 100011110 - * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1 - * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11 - * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11 - * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011 - * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111 - * - * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed - * because we are rounding 100011.1011011011011011 which rounds up. - * - * @method Phaser.Math#roundTo - * @param {number} value - The value to round. - * @param {number} place - The place to round to. - * @param {number} base - The base to round in... default is 10 for decimal. - * @return {number} - */ - roundTo: function (value, place, base) { - - if (typeof place === "undefined") { place = 0; } - if (typeof base === "undefined") { base = 10; } - - var p = Math.pow(base, -place); - - return Math.round(value * p) / p; - - }, - - /** - * @method Phaser.Math#floorTo - * @param {number} value - The value to round. - * @param {number} place - The place to round to. - * @param {number} base - The base to round in... default is 10 for decimal. - * @return {number} - */ - floorTo: function (value, place, base) { - - if (typeof place === "undefined") { place = 0; } - if (typeof base === "undefined") { base = 10; } - - var p = Math.pow(base, -place); - - return Math.floor(value * p) / p; - - }, - - /** - * @method Phaser.Math#ceilTo - * @param {number} value - The value to round. - * @param {number} place - The place to round to. - * @param {number} base - The base to round in... default is 10 for decimal. - * @return {number} - */ - ceilTo: function (value, place, base) { - - if (typeof place === "undefined") { place = 0; } - if (typeof base === "undefined") { base = 10; } - - var p = Math.pow(base, -place); - - return Math.ceil(value * p) / p; - - }, - - /** - * A one dimensional linear interpolation of a value. - * @method Phaser.Math#interpolateFloat - * @param {number} a - * @param {number} b - * @param {number} weight - * @return {number} - */ - interpolateFloat: function (a, b, weight) { - return (b - a) * weight + a; - }, - - /** - * Find the angle of a segment from (x1, y1) -> (x2, y2 ). - * @method Phaser.Math#angleBetween - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @return {number} - */ - angleBetween: function (x1, y1, x2, y2) { - return Math.atan2(y2 - y1, x2 - x1); - }, - - /** - * Set an angle within the bounds of -π toπ. - * @method Phaser.Math#normalizeAngle - * @param {number} angle - * @param {boolean} radians - True if angle size is expressed in radians. - * @return {number} - */ - normalizeAngle: function (angle, radians) { - - if (typeof radians === "undefined") { radians = true; } - - var rd = (radians) ? Math.PI : 180; - return this.wrap(angle, rd, -rd); - - }, - - /** - * Closest angle between two angles from a1 to a2 - * absolute value the return for exact angle - * @method Phaser.Math#nearestAngleBetween - * @param {number} a1 - * @param {number} a2 - * @param {boolean} radians - True if angle sizes are expressed in radians. - * @return {number} - */ - nearestAngleBetween: function (a1, a2, radians) { - - if (typeof radians === "undefined") { radians = true; } - - var rd = (radians) ? Math.PI : 180; - a1 = this.normalizeAngle(a1, radians); - a2 = this.normalizeAngle(a2, radians); - - if (a1 < -rd / 2 && a2 > rd / 2) - { - a1 += rd * 2; - } - - if (a2 < -rd / 2 && a1 > rd / 2) - { - a2 += rd * 2; - } - - return a2 - a1; - - }, - - /** - * Interpolate across the shortest arc between two angles. - * @method Phaser.Math#interpolateAngles - * @param {number} a1 - Description. - * @param {number} a2 - Description. - * @param {number} weight - Description. - * @param {boolean} radians - True if angle sizes are expressed in radians. - * @param {Description} ease - Description. - * @return {number} - */ - interpolateAngles: function (a1, a2, weight, radians, ease) { - - if (typeof radians === "undefined") { radians = true; } - if (typeof ease === "undefined") { ease = null; } - - a1 = this.normalizeAngle(a1, radians); - a2 = this.normalizeAngleToAnother(a2, a1, radians); - - return (typeof ease === 'function') ? ease(weight, a1, a2 - a1, 1) : this.interpolateFloat(a1, a2, weight); - - }, - - /** - * Generate a random bool result based on the chance value. - *

- * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance - * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed. - *

- * @method Phaser.Math#chanceRoll - * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%). - * @return {boolean} True if the roll passed, or false otherwise. - */ - chanceRoll: function (chance) { - - if (typeof chance === "undefined") { chance = 50; } - - if (chance <= 0) - { - return false; - } - else if (chance >= 100) - { - return true; - } - else - { - if (Math.random() * 100 >= chance) - { - return false; - } - else - { - return true; - } - } - - }, - - /** - * Returns an Array containing the numbers from min to max (inclusive). - * - * @method Phaser.Math#numberArray - * @param {number} min - The minimum value the array starts with. - * @param {number} max - The maximum value the array contains. - * @return {array} The array of number values. - */ - numberArray: function (min, max) { - - var result = []; - - for (var i = min; i <= max; i++) - { - result.push(i); - } - - return result; - - }, - - /** - * Adds the given amount to the value, but never lets the value go over the specified maximum. - * - * @method Phaser.Math#maxAdd - * @param {number} value - The value to add the amount to. - * @param {number} amount - The amount to add to the value. - * @param {number} max- The maximum the value is allowed to be. - * @return {number} - */ - maxAdd: function (value, amount, max) { - - value += amount; - - if (value > max) - { - value = max; - } - - return value; - - }, - - /** - * Subtracts the given amount from the value, but never lets the value go below the specified minimum. - * - * @method Phaser.Math#minSub - * @param {number} value - The base value. - * @param {number} amount - The amount to subtract from the base value. - * @param {number} min - The minimum the value is allowed to be. - * @return {number} The new value. - */ - minSub: function (value, amount, min) { - - value -= amount; - - if (value < min) - { - value = min; - } - - return value; - - }, - - /** - * Ensures that the value always stays between min and max, by wrapping the value around. - *

max should be larger than min, or the function will return 0

- * - * @method Phaser.Math#wrap - * @param value The value to wrap - * @param min The minimum the value is allowed to be - * @param max The maximum the value is allowed to be - * @return {number} The wrapped value - */ - wrap: function (value, min, max) { - - var range = max - min; - - if (range <= 0) - { - return 0; - } - - var result = (value - min) % range; - - if (result < 0) - { - result += range; - } - - return result + min; - - }, - - /** - * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around. - *

Values must be positive integers, and are passed through Math.abs

- * - * @method Phaser.Math#wrapValue - * @param {number} value - The value to add the amount to. - * @param {number} amount - The amount to add to the value. - * @param {number} max - The maximum the value is allowed to be. - * @return {number} The wrapped value. - */ - wrapValue: function (value, amount, max) { - - var diff; - value = Math.abs(value); - amount = Math.abs(amount); - max = Math.abs(max); - diff = (value + amount) % max; - - return diff; - - }, - - /** - * Randomly returns either a 1 or -1. - * - * @method Phaser.Math#randomSign - * @return {number} 1 or -1 - */ - randomSign: function () { - return (Math.random() > 0.5) ? 1 : -1; - }, - - /** - * Returns true if the number given is odd. - * - * @method Phaser.Math#isOdd - * @param {number} n - The number to check. - * @return {boolean} True if the given number is odd. False if the given number is even. - */ - isOdd: function (n) { - - return (n & 1); - - }, - - /** - * Returns true if the number given is even. - * - * @method Phaser.Math#isEven - * @param {number} n - The number to check. - * @return {boolean} True if the given number is even. False if the given number is odd. - */ - isEven: function (n) { - - if (n & 1) - { - return false; - } - else - { - return true; - } - - }, - - /** - * Significantly faster version of Math.max - * See http://jsperf.com/math-s-min-max-vs-homemade/5 - * - * @method Phaser.Math#max - * @return {number} The highest value from those given. - */ - max: function () { - - for (var i = 1, max = 0, len = arguments.length; i < len; i++) - { - if (arguments[max] < arguments[i]) - { - max = i; - } - } - - return arguments[max]; - - }, - - /** - * Significantly faster version of Math.min - * See http://jsperf.com/math-s-min-max-vs-homemade/5 - * - * @method Phaser.Math#min - * @return {number} The lowest value from those given. - */ - min: function () { - - for (var i =1 , min = 0, len = arguments.length; i < len; i++) - { - if (arguments[i] < arguments[min]) - { - min = i; - } - } - - return arguments[min]; - - }, - - /** - * Keeps an angle value between -180 and +180
- * Should be called whenever the angle is updated on the Sprite to stop it from going insane. - * - * @method Phaser.Math#wrapAngle - * @param {number} angle - The angle value to check - * @return {number} The new angle value, returns the same as the input angle if it was within bounds. - */ - wrapAngle: function (angle) { - - var result = angle; - - // Nothing needs to change - if (angle >= -180 && angle <= 180) - { - return angle; - } - - // Else normalise it to -180, 180 - result = (angle + 180) % 360; - - if (result < 0) - { - result += 360; - } - - return result - 180; - - }, - - /** - * Keeps an angle value between the given min and max values. - * - * @method Phaser.Math#angleLimit - * @param {number} angle - The angle value to check. Must be between -180 and +180. - * @param {number} min - The minimum angle that is allowed (must be -180 or greater). - * @param {number} max - The maximum angle that is allowed (must be 180 or less). - * - * @return {number} The new angle value, returns the same as the input angle if it was within bounds - */ - angleLimit: function (angle, min, max) { - - var result = angle; - - if (angle > max) - { - result = max; - } - else if (angle < min) - { - result = min; - } - - return result; - - }, - - /** - * Description. - * @method Phaser.Math#linearInterpolation - * @param {number} v - * @param {number} k - * @return {number} - */ - linearInterpolation: function (v, k) { - - var m = v.length - 1; - var f = m * k; - var i = Math.floor(f); - - if (k < 0) - { - return this.linear(v[0], v[1], f); - } - - if (k > 1) - { - return this.linear(v[m], v[m - 1], m - f); - } - - return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i); - - }, - - /** - * Description. - * @method Phaser.Math#bezierInterpolation - * @param {number} v - * @param {number} k - * @return {number} - */ - bezierInterpolation: function (v, k) { - - var b = 0; - var n = v.length - 1; - - for (var i = 0; i <= n; i++) - { - b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i); - } - - return b; - - }, - - /** - * Description. - * @method Phaser.Math#catmullRomInterpolation - * @param {number} v - * @param {number} k - * @return {number} - */ - catmullRomInterpolation: function (v, k) { - - var m = v.length - 1; - var f = m * k; - var i = Math.floor(f); - - if (v[0] === v[m]) - { - if (k < 0) - { - i = Math.floor(f = m * (1 + k)); - } - - return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); - - } - else - { - if (k < 0) - { - return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]); - } - - if (k > 1) - { - return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]); - } - - return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); - } - - }, - - /** - * Description. - * @method Phaser.Math#Linear - * @param {number} p0 - * @param {number} p1 - * @param {number} t - * @return {number} - */ - linear: function (p0, p1, t) { - return (p1 - p0) * t + p0; - }, - - /** - * @method Phaser.Math#bernstein - * @param {number} n - * @param {number} i - * @return {number} - */ - bernstein: function (n, i) { - return this.factorial(n) / this.factorial(i) / this.factorial(n - i); - }, - - /** - * Description. - * @method Phaser.Math#catmullRom - * @param {number} p0 - * @param {number} p1 - * @param {number} p2 - * @param {number} p3 - * @param {number} t - * @return {number} - */ - catmullRom: function (p0, p1, p2, p3, t) { - - var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2; - - return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; - - }, - - /** - * @method Phaser.Math#difference - * @param {number} a - * @param {number} b - * @return {number} - */ - difference: function (a, b) { - return Math.abs(a - b); - }, - - /** - * Fetch a random entry from the given array. - * Will return null if random selection is missing, or array has no entries. - * - * @method Phaser.Math#getRandom - * @param {array} objects - An array of objects. - * @param {number} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array. - * @param {number} length - Optional restriction on the number of values you want to randomly select from. - * @return {object} The random object that was selected. - */ - getRandom: function (objects, startIndex, length) { - - if (typeof startIndex === "undefined") { startIndex = 0; } - if (typeof length === "undefined") { length = 0; } - - if (objects != null) { - - var l = length; - - if ((l == 0) || (l > objects.length - startIndex)) - { - l = objects.length - startIndex; - } - - if (l > 0) - { - return objects[startIndex + Math.floor(Math.random() * l)]; - } - } - - return null; - - }, - - /** - * Round down to the next whole number. E.g. floor(1.7) == 1, and floor(-2.7) == -2. - * - * @method Phaser.Math#floor - * @param {number} Value Any number. - * @return {number} The rounded value of that number. - */ - floor: function (value) { - - var n = value | 0; - - return (value > 0) ? (n) : ((n != value) ? (n - 1) : (n)); - - }, - - /** - * Round up to the next whole number. E.g. ceil(1.3) == 2, and ceil(-2.3) == -3. - * - * @method Phaser.Math#ceil - * @param {number} value - Any number. - * @return {number} The rounded value of that number. - */ - ceil: function (value) { - var n = value | 0; - return (value > 0) ? ((n != value) ? (n + 1) : (n)) : (n); - }, - - /** - * Generate a sine and cosine table simultaneously and extremely quickly. Based on research by Franky of scene.at - *

- * The parameters allow you to specify the length, amplitude and frequency of the wave. Once you have called this function - * you should get the results via getSinTable() and getCosTable(). This generator is fast enough to be used in real-time. - *

- * @method Phaser.Math#sinCosGenerator - * @param {number} length - The length of the wave - * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value - * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value - * @param {number} frequency - The frequency of the sine and cosine table data - * @return {Array} Returns the sine table - */ - sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) { - - if (typeof sinAmplitude === "undefined") { sinAmplitude = 1.0; } - if (typeof cosAmplitude === "undefined") { cosAmplitude = 1.0; } - if (typeof frequency === "undefined") { frequency = 1.0; } - - var sin = sinAmplitude; - var cos = cosAmplitude; - var frq = frequency * Math.PI / length; - - var cosTable = []; - var sinTable = []; - - for (var c = 0; c < length; c++) { - - cos -= sin * frq; - sin += cos * frq; - - cosTable[c] = cos; - sinTable[c] = sin; - - } - - return { sin: sinTable, cos: cosTable, length: length }; - - }, - - /** - * Removes the top element from the stack and re-inserts it onto the bottom, then returns it. - * The original stack is modified in the process. This effectively moves the position of the data from the start to the end of the table. - * - * @method Phaser.Math#shift - * @param {array} stack - The array to shift. - * @return {any} The shifted value. - */ - shift: function (stack) { - - var s = stack.shift(); - stack.push(s); - - return s; - - }, - - /** - * Shuffles the data in the given array into a new order - * @method Phaser.Math#shuffleArray - * @param {array} array - The array to shuffle - * @return {array} The array - */ - shuffleArray: function (array) { - - for (var i = array.length - 1; i > 0; i--) { - - var j = Math.floor(Math.random() * (i + 1)); - var temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - return array; - - }, - - /** - * Returns the distance between the two given set of coordinates. - * - * @method Phaser.Math#distance - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @return {number} The distance between this Point object and the destination Point object. - **/ - distance: function (x1, y1, x2, y2) { - - var dx = x1 - x2; - var dy = y1 - y2; - - return Math.sqrt(dx * dx + dy * dy); - - }, - - /** - * Returns the rounded distance between the two given set of coordinates. - * - * @method Phaser.Math#distanceRounded - * @param {number} x1 - * @param {number} y1 - * @param {number} x2 - * @param {number} y2 - * @return {number} The distance between this Point object and the destination Point object. - **/ - distanceRounded: function (x1, y1, x2, y2) { - - return Math.round(Phaser.Math.distance(x1, y1, x2, y2)); - - }, - - /** - * Force a value within the boundaries of two values. - * Clamp value to range - * - * @method Phaser.Math#clamp - * @param {number} x - * @param {number} a - * @param {number} b - * @return {number} - */ - clamp: function ( x, a, b ) { - - return ( x < a ) ? a : ( ( x > b ) ? b : x ); - - }, - - /** - * Clamp value to range to range - * - * @method Phaser.Math#mapLinear - * @param {number} x - * @param {number} a1 - * @param {number} a1 - * @param {number} a2 - * @param {number} b1 - * @param {number} b2 - * @return {number} - */ - mapLinear: function ( x, a1, a2, b1, b2 ) { - - return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 ); - - }, - - /** - * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep - * - * @method Phaser.Math#smoothstep - * @param {number} x - * @param {number} min - * @param {number} max - * @return {number} - */ - smoothstep: function ( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min )/( max - min ); - - return x*x*(3 - 2*x); - - }, - - /** - * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep - * - * @method Phaser.Math#smootherstep - * @param {number} x - * @param {number} min - * @param {number} max - * @return {number} - */ - smootherstep: function ( x, min, max ) { - - if ( x <= min ) return 0; - if ( x >= max ) return 1; - - x = ( x - min )/( max - min ); - - return x*x*x*(x*(x*6 - 15) + 10); - - }, - - /** - * A value representing the sign of the value. - * -1 for negative, +1 for positive, 0 if value is 0 - * - * @method Phaser.Math#sign - * @param {number} x - * @return {number} - */ - sign: function ( x ) { - - return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 ); - - }, - - /** - * Convert degrees to radians. - * - * @method Phaser.Math#degToRad - * @return {function} - */ - degToRad: function() { - - var degreeToRadiansFactor = Math.PI / 180; - - return function ( degrees ) { - - return degrees * degreeToRadiansFactor; - - }; - - }(), - - /** - * Convert degrees to radians. - * - * @method Phaser.Math#radToDeg - * @return {function} - */ - radToDeg: function() { - - var radianToDegreesFactor = 180 / Math.PI; - - return function ( radians ) { - - return radians * radianToDegreesFactor; - - }; - - }() - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** - * Javascript QuadTree - * @version 1.0 - * @author Timo Hausmann - * - * @version 1.2, September 4th 2013 - * @author Richard Davey - * The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked - * it massively to add node indexing, removed lots of temp. var creation and significantly - * increased performance as a result. - * - * Original version at https://github.com/timohausmann/quadtree-js/ - */ - -/** -* @copyright © 2012 Timo Hausmann -* -* Permission is hereby granted, free of charge, to any person obtaining -* a copy of this software and associated documentation files (the -* "Software"), to deal in the Software without restriction, including -* without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to -* permit persons to whom the Software is furnished to do so, subject to -* the following conditions: -* -* The above copyright notice and this permission notice shall be -* included in all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -/** - * QuadTree Constructor - * - * @class Phaser.QuadTree - * @classdesc A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked - * it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result. Original version at https://github.com/timohausmann/quadtree-js/ - * @constructor - * @param {Description} physicsManager - Description. - * @param {Description} x - Description. - * @param {Description} y - Description. - * @param {number} width - The width of your game in game pixels. - * @param {number} height - The height of your game in game pixels. - * @param {number} maxObjects - Description. - * @param {number} maxLevels - Description. - * @param {number} level - Description. - */ -Phaser.QuadTree = function (physicsManager, x, y, width, height, maxObjects, maxLevels, level) { - - this.physicsManager = physicsManager; - this.ID = physicsManager.quadTreeID; - physicsManager.quadTreeID++; - - this.maxObjects = maxObjects || 10; - this.maxLevels = maxLevels || 4; - this.level = level || 0; - - this.bounds = { - x: Math.round(x), - y: Math.round(y), - width: width, - height: height, - subWidth: Math.floor(width / 2), - subHeight: Math.floor(height / 2), - right: Math.round(x) + Math.floor(width / 2), - bottom: Math.round(y) + Math.floor(height / 2) - }; - - this.objects = []; - this.nodes = []; - -}; - -Phaser.QuadTree.prototype = { - - /* - * Split the node into 4 subnodes - * - * @method Phaser.QuadTree#split - */ - split: function() { - - this.level++; - - // top right node - this.nodes[0] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - // top left node - this.nodes[1] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - // bottom left node - this.nodes[2] = new Phaser.QuadTree(this.physicsManager, this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - // bottom right node - this.nodes[3] = new Phaser.QuadTree(this.physicsManager, this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, this.level); - - }, - - /* - * Insert the object into the node. If the node - * exceeds the capacity, it will split and add all - * objects to their corresponding subnodes. - * - * @method Phaser.QuadTree#insert - * @param {object} body - Description. - */ - insert: function (body) { - - var i = 0; - var index; - - // if we have subnodes ... - if (this.nodes[0] != null) - { - index = this.getIndex(body); - - if (index !== -1) - { - this.nodes[index].insert(body); - return; - } - } - - this.objects.push(body); - - if (this.objects.length > this.maxObjects && this.level < this.maxLevels) - { - // Split if we don't already have subnodes - if (this.nodes[0] == null) - { - this.split(); - } - - // Add objects to subnodes - while (i < this.objects.length) - { - index = this.getIndex(this.objects[i]); - - if (index !== -1) - { - // this is expensive - see what we can do about it - this.nodes[index].insert(this.objects.splice(i, 1)[0]); - } - else - { - i++; - } - } - } - }, - - /* - * Determine which node the object belongs to. - * - * @method Phaser.QuadTree#getIndex - * @param {object} rect - Description. - * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node. - */ - getIndex: function (rect) { - - // default is that rect doesn't fit, i.e. it straddles the internal quadrants - var index = -1; - - if (rect.x < this.bounds.right && rect.right < this.bounds.right) - { - if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)) - { - // rect fits within the top-left quadrant of this quadtree - index = 1; - } - else if ((rect.y > this.bounds.bottom)) - { - // rect fits within the bottom-left quadrant of this quadtree - index = 2; - } - } - else if (rect.x > this.bounds.right) - { - // rect can completely fit within the right quadrants - if ((rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)) - { - // rect fits within the top-right quadrant of this quadtree - index = 0; - } - else if ((rect.y > this.bounds.bottom)) - { - // rect fits within the bottom-right quadrant of this quadtree - index = 3; - } - } - - return index; - - }, - - /* - * Return all objects that could collide with the given object. - * - * @method Phaser.QuadTree#retrieve - * @param {object} rect - Description. - * @Return {array} - Array with all detected objects. - */ - retrieve: function (sprite) { - - var returnObjects = this.objects; - - sprite.body.quadTreeIndex = this.getIndex(sprite.body); - - // Temp store for the node IDs this sprite is in, we can use this for fast elimination later - sprite.body.quadTreeIDs.push(this.ID); - - if (this.nodes[0]) - { - // if rect fits into a subnode .. - if (sprite.body.quadTreeIndex !== -1) - { - returnObjects = returnObjects.concat(this.nodes[sprite.body.quadTreeIndex].retrieve(sprite)); - } - else - { - // if rect does not fit into a subnode, check it against all subnodes (unrolled for speed) - returnObjects = returnObjects.concat(this.nodes[0].retrieve(sprite)); - returnObjects = returnObjects.concat(this.nodes[1].retrieve(sprite)); - returnObjects = returnObjects.concat(this.nodes[2].retrieve(sprite)); - returnObjects = returnObjects.concat(this.nodes[3].retrieve(sprite)); - } - } - - return returnObjects; - - }, - - /* - * Clear the quadtree. - * @method Phaser.QuadTree#clear - */ - clear: function () { - - this.objects = []; - - for (var i = 0, len = this.nodes.length; i < len; i++) - { - // if (typeof this.nodes[i] !== 'undefined') - if (this.nodes[i]) - { - this.nodes[i].clear(); - delete this.nodes[i]; - } - } - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter. If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created. -* @class Circle -* @classdesc Phaser - Circle -* @constructor -* @param {number} [x] The x coordinate of the center of the circle. -* @param {number} [y] The y coordinate of the center of the circle. -* @param {number} [diameter] The diameter of the circle. -* @return {Phaser.Circle} This circle object -**/ -Phaser.Circle = function (x, y, diameter) { - - x = x || 0; - y = y || 0; - diameter = diameter || 0; - - /** - * @property {number} x - The x coordinate of the center of the circle. - **/ - this.x = x; - - /** - * @property {number} y - The y coordinate of the center of the circle. - **/ - this.y = y; - - /** - * @property {number} _diameter - The diameter of the circle. - * @private - **/ - this._diameter = diameter; - - if (diameter > 0) - { - /** - * @property {number} _radius - The radius of the circle. - * @private - **/ - this._radius = diameter * 0.5; - } - else - { - this._radius = 0; - } - -}; - -Phaser.Circle.prototype = { - - /** - * The circumference of the circle. - * @method Phaser.Circle#circumference - * @return {number} - **/ - circumference: function () { - return 2 * (Math.PI * this._radius); - }, - - /** - * Sets the members of Circle to the specified values. - * @method Phaser.Circle#setTo - * @param {number} x - The x coordinate of the center of the circle. - * @param {number} y - The y coordinate of the center of the circle. - * @param {number} diameter - The diameter of the circle in pixels. - * @return {Circle} This circle object. - **/ - setTo: function (x, y, diameter) { - this.x = x; - this.y = y; - this._diameter = diameter; - this._radius = diameter * 0.5; - return this; - }, - - /** - * Copies the x, y and diameter properties from any given object to this Circle. - * @method Phaser.Circle#copyFrom - * @param {any} source - The object to copy from. - * @return {Circle} This Circle object. - **/ - copyFrom: function (source) { - return this.setTo(source.x, source.y, source.diameter); - }, - - /** - * Copies the x, y and diameter properties from this Circle to any given object. - * @method Phaser.Circle#copyTo - * @param {any} dest - The object to copy to. - * @return {Object} This dest object. - **/ - copyTo: function(dest) { - dest[x] = this.x; - dest[y] = this.y; - dest[diameter] = this._diameter; - return dest; - }, - - /** - * Returns the distance from the center of the Circle object to the given object - * (can be Circle, Point or anything with x/y properties) - * @method Phaser.Circle#distance - * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. - * @param {boolean} [round] - Round the distance to the nearest integer (default false). - * @return {number} The distance between this Point object and the destination Point object. - */ - distance: function (dest, round) { - - if (typeof round === "undefined") { round = false } - - if (round) - { - return Phaser.Math.distanceRound(this.x, this.y, dest.x, dest.y); - } - else - { - return Phaser.Math.distance(this.x, this.y, dest.x, dest.y); - } - - }, - - /** - * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object. - * @method Phaser.Circle#clone - * @param {Phaser.Circle} out - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned. - * @return {Phaser.Circle} The cloned Circle object. - */ - clone: function(out) { - - if (typeof out === "undefined") { out = new Phaser.Circle(); } - - return out.setTo(a.x, a.y, a.diameter); - - }, - - /** - * Return true if the given x/y coordinates are within this Circle object. - * @method Phaser.Circle#contains - * @param {number} x - The X value of the coordinate to test. - * @param {number} y - The Y value of the coordinate to test. - * @return {boolean} True if the coordinates are within this circle, otherwise false. - */ - contains: function (x, y) { - return Phaser.Circle.contains(this, x, y); - }, - - /** - * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. - * @method Phaser.Circle#circumferencePoint - * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. - * @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)? - * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. - * @return {Phaser.Point} The Point object holding the result. - */ - circumferencePoint: function (angle, asDegrees, out) { - return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out); - }, - - /** - * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts. - * @method Phaser.Circle#offset - * @param {number} dx - Moves the x value of the Circle object by this amount. - * @param {number} dy - Moves the y value of the Circle object by this amount. - * @return {Circle} This Circle object. - **/ - offset: function (dx, dy) { - this.x += dx; - this.y += dy; - return this; - }, - - /** - * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter. - * @method Phaser.Circle#offsetPoint - * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties). - * @return {Circle} This Circle object. - **/ - offsetPoint: function (point) { - return this.offset(point.x, point.y); - }, - - /** - * Returns a string representation of this object. - * @method Phaser.Circle#toString - * @return {string} a string representation of the instance. - **/ - toString: function () { - return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]"; - } - -}; - -/** -* The largest distance between any two points on the circle. The same as the radius * 2. -* @name Phaser.Circle#diameter -* @property {number} diameter - Gets or sets the diameter of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "diameter", { - - get: function () { - return this._diameter; - }, - - set: function (value) { - if (value > 0) { - this._diameter = value; - this._radius = value * 0.5; - } - } - -}); - -/** -* The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter. -* @name Phaser.Circle#radius -* @property {number} radius - Gets or sets the radius of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "radius", { - - get: function () { - return this._radius; - }, - - set: function (value) { - if (value > 0) { - this._radius = value; - this._diameter = value * 2; - } - } - -}); - -/** -* The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. -* @name Phaser.Circle#left -* @propety {number} left - Gets or sets the value of the leftmost point of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "left", { - - get: function () { - return this.x - this._radius; - }, - - set: function (value) { - if (value > this.x) { - this._radius = 0; - this._diameter = 0; - } else { - this.radius = this.x - value; - } - } - -}); - -/** -* The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property. -* @name Phaser.Circle#right -* @property {number} right - Gets or sets the value of the rightmost point of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "right", { - - get: function () { - return this.x + this._radius; - }, - - set: function (value) { - if (value < this.x) { - this._radius = 0; - this._diameter = 0; - } else { - this.radius = value - this.x; - } - } - -}); - -/** -* The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter. -* @name Phaser.Circle#top -* @property {number} top - Gets or sets the top of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "top", { - - get: function () { - return this.y - this._radius; - }, - - set: function (value) { - if (value > this.y) { - this._radius = 0; - this._diameter = 0; - } else { - this.radius = this.y - value; - } - } - -}); - -/** -* The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter. -* @name Phaser.Circle#bottom -* @property {number} bottom - Gets or sets the bottom of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "bottom", { - - get: function () { - return this.y + this._radius; - }, - - set: function (value) { - - if (value < this.y) { - this._radius = 0; - this._diameter = 0; - } else { - this.radius = value - this.y; - } - } - -}); - -/** -* The area of this Circle. -* @name Phaser.Circle#area -* @property {number} area - The area of this circle. -* @readonly -*/ -Object.defineProperty(Phaser.Circle.prototype, "area", { - - get: function () { - if (this._radius > 0) { - return Math.PI * this._radius * this._radius; - } else { - return 0; - } - } - -}); - -/** -* Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false. -* If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0. -* @name Phaser.Circle#empty -* @property {boolean} empty - Gets or sets the empty state of the circle. -*/ -Object.defineProperty(Phaser.Circle.prototype, "empty", { - - get: function () { - return (this._diameter == 0); - }, - - set: function (value) { - this.setTo(0, 0, 0); - } - -}); - -/** -* Return true if the given x/y coordinates are within the Circle object. -* @method Phaser.Circle.contains -* @param {Phaser.Circle} a - The Circle to be checked. -* @param {number} x - The X value of the coordinate to test. -* @param {number} y - The Y value of the coordinate to test. -* @return {boolean} True if the coordinates are within this circle, otherwise false. -*/ -Phaser.Circle.contains = function (a, x, y) { - - // Check if x/y are within the bounds first - if (x >= a.left && x <= a.right && y >= a.top && y <= a.bottom) { - - var dx = (a.x - x) * (a.x - x); - var dy = (a.y - y) * (a.y - y); - - return (dx + dy) <= (a.radius * a.radius); - - } - - return false; - -}; - -/** -* Determines whether the two Circle objects match. This method compares the x, y and diameter properties. -* @method Phaser.Circle.equals -* @param {Phaser.Circle} a - The first Circle object. -* @param {Phaser.Circle} b - The second Circle object. -* @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false. -*/ -Phaser.Circle.equals = function (a, b) { - return (a.x == b.x && a.y == b.y && a.diameter == b.diameter); -}; - -/** -* Determines whether the two Circle objects intersect. -* This method checks the radius distances between the two Circle objects to see if they intersect. -* @method Phaser.Circle.intersects -* @param {Phaser.Circle} a - The first Circle object. -* @param {Phaser.Circle} b - The second Circle object. -* @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false. -*/ -Phaser.Circle.intersects = function (a, b) { - return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius)); -}; - -/** -* Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle. -* @method Phaser.Circle.circumferencePoint -* @param {Phaser.Circle} a - The first Circle object. -* @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from. -* @param {boolean} asDegrees - Is the given angle in radians (false) or degrees (true)? -* @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created. -* @return {Phaser.Point} The Point object holding the result. -*/ -Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) { - - if (typeof asDegrees === "undefined") { asDegrees = false; } - if (typeof out === "undefined") { out = new Phaser.Point(); } - - if (asDegrees === true) { - angle = Phaser.Math.radToDeg(angle); - } - - out.x = a.x + a.radius * Math.cos(angle); - out.y = a.y + a.radius * Math.sin(angle); - - return out; - -}; - -/** -* Checks if the given Circle and Rectangle objects intersect. -* @method Phaser.Circle.intersectsRectangle -* @param {Phaser.Circle} c - The Circle object to test. -* @param {Phaser.Rectangle} r - The Rectangle object to test. -* @return {boolean} True if the two objects intersect, otherwise false. -*/ -Phaser.Circle.intersectsRectangle = function (c, r) { - - var cx = Math.abs(c.x - r.x - r.halfWidth); - var xDist = r.halfWidth + c.radius; - - if (cx > xDist) { - return false; - } - - var cy = Math.abs(c.y - r.y - r.halfHeight); - var yDist = r.halfHeight + c.radius; - - if (cy > yDist) { - return false; - } - - if (cx <= r.halfWidth || cy <= r.halfHeight) { - return true; - } - - var xCornerDist = cx - r.halfWidth; - var yCornerDist = cy - r.halfHeight; - var xCornerDistSq = xCornerDist * xCornerDist; - var yCornerDistSq = yCornerDist * yCornerDist; - var maxCornerDistSq = c.radius * c.radius; - - return xCornerDistSq + yCornerDistSq <= maxCornerDistSq; - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new Point. If you pass no parameters a Point is created set to (0,0). -* @class Phaser.Point -* @classdesc The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis. -* @constructor -* @param {number} x The horizontal position of this Point (default 0) -* @param {number} y The vertical position of this Point (default 0) -**/ -Phaser.Point = function (x, y) { - - x = x || 0; - y = y || 0; - - /** - * @property {number} x - The x coordinate of the point. - **/ - this.x = x; - - /** - * @property {number} y - The y coordinate of the point. - **/ - this.y = y; - -}; - -Phaser.Point.prototype = { - - /** - * Copies the x and y properties from any given object to this Point. - * @method Phaser.Point#copyFrom - * @param {any} source - The object to copy from. - * @return {Point} This Point object. - **/ - copyFrom: function (source) { - return this.setTo(source.x, source.y); - }, - - /** - * Inverts the x and y values of this Point - * @method Phaser.Point#invert - * @return {Point} This Point object. - **/ - invert: function () { - return this.setTo(this.y, this.x); - }, - - /** - * Sets the x and y values of this Point object to the given coordinates. - * @method Phaser.Point#setTo - * @param {number} x - The horizontal position of this point. - * @param {number} y - The vertical position of this point. - * @return {Point} This Point object. Useful for chaining method calls. - **/ - setTo: function (x, y) { - - this.x = x; - this.y = y; - return this; - - }, - - /** - * Adds the given x and y values to this Point. - * @method Phaser.Point#add - * @param {number} x - The value to add to Point.x. - * @param {number} y - The value to add to Point.y. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - **/ - add: function (x, y) { - - this.x += x; - this.y += y; - return this; - - }, - - /** - * Subtracts the given x and y values from this Point. - * @method Phaser.Point#subtract - * @param {number} x - The value to subtract from Point.x. - * @param {number} y - The value to subtract from Point.y. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - **/ - subtract: function (x, y) { - - this.x -= x; - this.y -= y; - return this; - - }, - - /** - * Multiplies Point.x and Point.y by the given x and y values. - * @method Phaser.Point#multiply - * @param {number} x - The value to multiply Point.x by. - * @param {number} y - The value to multiply Point.x by. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - **/ - multiply: function (x, y) { - - this.x *= x; - this.y *= y; - return this; - - }, - - /** - * Divides Point.x and Point.y by the given x and y values. - * @method Phaser.Point#divide - * @param {number} x - The value to divide Point.x by. - * @param {number} y - The value to divide Point.x by. - * @return {Phaser.Point} This Point object. Useful for chaining method calls. - **/ - divide: function (x, y) { - - this.x /= x; - this.y /= y; - return this; - - }, - - /** - * Clamps the x value of this Point to be between the given min and max. - * @method Phaser.Point#clampX - * @param {number} min - The minimum value to clamp this Point to. - * @param {number} max - The maximum value to clamp this Point to. - * @return {Phaser.Point} This Point object. - */ - clampX: function (min, max) { - - this.x = Phaser.Math.clamp(this.x, min, max); - return this; - - }, - - /** - * Clamps the y value of this Point to be between the given min and max - * @method Phaser.Point#clampY - * @param {number} min - The minimum value to clamp this Point to. - * @param {number} max - The maximum value to clamp this Point to. - * @return {Phaser.Point} This Point object. - */ - clampY: function (min, max) { - - this.y = Phaser.Math.clamp(this.y, min, max); - return this; - - }, - - /** - * Clamps this Point object values to be between the given min and max. - * @method Phaser.Point#clamp - * @param {number} min - The minimum value to clamp this Point to. - * @param {number} max - The maximum value to clamp this Point to. - * @return {Phaser.Point} This Point object. - */ - clamp: function (min, max) { - - this.x = Phaser.Math.clamp(this.x, min, max); - this.y = Phaser.Math.clamp(this.y, min, max); - return this; - - }, - - /** - * Creates a copy of the given Point. - * @method Phaser.Point#clone - * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned. - * @return {Phaser.Point} The new Point object. - */ - clone: function (output) { - - if (typeof output === "undefined") { output = new Phaser.Point; } - - return output.setTo(this.x, this.y); - - }, - - /** - * Copies the x and y properties from any given object to this Point. - * @method Phaser.Point#copyFrom - * @param {any} source - The object to copy from. - * @return {Point} This Point object. - **/ - copyFrom: function (source) { - return this.setTo(source.x, source.y); - }, - - /** - * Copies the x and y properties from this Point to any given object. - * @method Phaser.Point#copyTo - * @param {any} dest - The object to copy to. - * @return {Object} The dest object. - **/ - copyTo: function(dest) { - - dest[x] = this.x; - dest[y] = this.y; - - return dest; - - }, - - /** - * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties) - * @method Phaser.Point#distance - * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object. - * @param {boolean} [round] - Round the distance to the nearest integer (default false). - * @return {number} The distance between this Point object and the destination Point object. - */ - distance: function (dest, round) { - return Phaser.Point.distance(this, dest, round); - }, - - /** - * Determines whether the given objects x/y values are equal to this Point object. - * @method Phaser.Point#equals - * @param {Phaser.Point} a - The first object to compare. - * @return {boolean} A value of true if the Points are equal, otherwise false. - */ - equals: function (a) { - return (a.x == this.x && a.y == this.y); - }, - - /** - * Rotates this Point around the x/y coordinates given to the desired angle. - * @method Phaser.Point#rotate - * @param {number} x - The x coordinate of the anchor point - * @param {number} y - The y coordinate of the anchor point - * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. - * @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)? - * @param {number} [distance] - An optional distance constraint between the Point and the anchor. - * @return {Phaser.Point} The modified point object. - */ - rotate: function (x, y, angle, asDegrees, distance) { - return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance); - }, - - /** - * Calculates the length of the vector - * @method Phaser.Point#getMagnitude - * @return {number} the length of the vector - */ - getMagnitude: function() { - return Math.sqrt((this.x * this.x) + (this.y * this.y)); - }, - - /** - * Alters the length of the vector without changing the direction - * @method Phaser.Point#getMagnitude - * @param {number} magnitude the desired magnitude of the resulting vector - * @return {Phaser.Point} the modified original vector - */ - setMagnitude: function(magnitude) { - return this.normalize().multiply(magnitude, magnitude); - }, - - /** - * Alters the vector so that its length is 1, but it retains the same direction - * @method Phaser.Point#normalize - * @return {Phaser.Point} the modified original vector - */ - normalize: function() { - - if(!this.isZero()) { - var m = this.getMagnitude(); - this.x /= m; - this.y /= m; - } - - return this; - - }, - - /** - * Determine if this point is at 0,0 - * @method Phaser.Point#isZero - * @return {boolean} True if this Point is 0,0, otherwise false - */ - isZero: function() { - return (this.x === 0 && this.y === 0); - }, - - /** - * Returns a string representation of this object. - * @method Phaser.Point#toString - * @return {string} A string representation of the instance. - **/ - toString: function () { - return '[{Point (x=' + this.x + ' y=' + this.y + ')}]'; - } - -}; - -/** -* Adds the coordinates of two points together to create a new point. -* @method Phaser.Point.add -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ -Phaser.Point.add = function (a, b, out) { - - if (typeof out === "undefined") { out = new Phaser.Point(); } - - out.x = a.x + b.x; - out.y = a.y + b.y; - - return out; - -}; - -/** -* Subtracts the coordinates of two points to create a new point. -* @method Phaser.Point.subtract -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ -Phaser.Point.subtract = function (a, b, out) { - - if (typeof out === "undefined") { out = new Phaser.Point(); } - - out.x = a.x - b.x; - out.y = a.y - b.y; - - return out; - -}; - -/** -* Multiplies the coordinates of two points to create a new point. -* @method Phaser.Point.multiply -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ -Phaser.Point.multiply = function (a, b, out) { - - if (typeof out === "undefined") { out = new Phaser.Point(); } - - out.x = a.x * b.x; - out.y = a.y * b.y; - - return out; - -}; - -/** -* Divides the coordinates of two points to create a new point. -* @method Phaser.Point.divide -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created. -* @return {Phaser.Point} The new Point object. -*/ -Phaser.Point.divide = function (a, b, out) { - - if (typeof out === "undefined") { out = new Phaser.Point(); } - - out.x = a.x / b.x; - out.y = a.y / b.y; - - return out; - -}; - -/** -* Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values. -* @method Phaser.Point.equals -* @param {Phaser.Point} a - The first Point object. -* @param {Phaser.Point} b - The second Point object. -* @return {boolean} A value of true if the Points are equal, otherwise false. -*/ -Phaser.Point.equals = function (a, b) { - return (a.x == b.x && a.y == b.y); -}; - -/** -* Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties). -* @method Phaser.Point.distance -* @param {object} a - The target object. Must have visible x and y properties that represent the center of the object. -* @param {object} b - The target object. Must have visible x and y properties that represent the center of the object. -* @param {boolean} [round] - Round the distance to the nearest integer (default false). -* @return {number} The distance between this Point object and the destination Point object. -*/ -Phaser.Point.distance = function (a, b, round) { - - if (typeof round === "undefined") { round = false } - - if (round) - { - return Phaser.Math.distanceRound(a.x, a.y, b.x, b.y); - } - else - { - return Phaser.Math.distance(a.x, a.y, b.x, b.y); - } - -}, - -/** -* Rotates a Point around the x/y coordinates given to the desired angle. -* @method Phaser.Point.rotate -* @param {Phaser.Point} a - The Point object to rotate. -* @param {number} x - The x coordinate of the anchor point -* @param {number} y - The y coordinate of the anchor point -* @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to. -* @param {boolean} asDegrees - Is the given rotation in radians (false) or degrees (true)? -* @param {number} distance - An optional distance constraint between the Point and the anchor. -* @return {Phaser.Point} The modified point object. -*/ -Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) { - - asDegrees = asDegrees || false; - distance = distance || null; - - if (asDegrees) - { - angle = Phaser.Math.degToRad(angle); - } - - // Get distance from origin (cx/cy) to this point - if (distance === null) - { - distance = Math.sqrt(((x - a.x) * (x - a.x)) + ((y - a.y) * (y - a.y))); - } - - return a.setTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle)); - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters. If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created. -* -* @class Phaser.Rectangle -* @constructor -* @param {number} x - The x coordinate of the top-left corner of the Rectangle. -* @param {number} y - The y coordinate of the top-left corner of the Rectangle. -* @param {number} width - The width of the Rectangle in pixels. -* @param {number} height - The height of the Rectangle in pixels. -* @return {Rectangle} This Rectangle object. -**/ -Phaser.Rectangle = function (x, y, width, height) { - - x = x || 0; - y = y || 0; - width = width || 0; - height = height || 0; - - /** - * @property {number} x - Description. - */ - this.x = x; - - /** - * @property {number} y - Description. - */ - this.y = y; - - /** - * @property {number} width - Description. - */ - this.width = width; - - /** - * @property {number} height - Description. - */ - this.height = height; - -}; - -Phaser.Rectangle.prototype = { - - /** - * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts. - * @method Phaser.Rectangle#offset - * @param {number} dx - Moves the x value of the Rectangle object by this amount. - * @param {number} dy - Moves the y value of the Rectangle object by this amount. - * @return {Rectangle} This Rectangle object. - **/ - offset: function (dx, dy) { - - this.x += dx; - this.y += dy; - - return this; - - }, - - /** - * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter. - * @method Phaser.Rectangle#offsetPoint - * @param {Point} point - A Point object to use to offset this Rectangle object. - * @return {Rectangle} This Rectangle object. - **/ - offsetPoint: function (point) { - return this.offset(point.x, point.y); - }, - - /** - * Sets the members of Rectangle to the specified values. - * @method Phaser.Rectangle#setTo - * @param {number} x - The x coordinate of the top-left corner of the Rectangle. - * @param {number} y - The y coordinate of the top-left corner of the Rectangle. - * @param {number} width - The width of the Rectangle in pixels. - * @param {number} height - The height of the Rectangle in pixels. - * @return {Rectangle} This Rectangle object - **/ - setTo: function (x, y, width, height) { - - this.x = x; - this.y = y; - this.width = width; - this.height = height; - - return this; - - }, - - /** - * Runs Math.floor() on both the x and y values of this Rectangle. - * @method Phaser.Rectangle#floor - **/ - floor: function () { - - this.x = Math.floor(this.x); - this.y = Math.floor(this.y); - - }, - - /** - * Runs Math.floor() on the x, y, width and height values of this Rectangle. - * @method Phaser.Rectangle#floorAll - **/ - floorAll: function () { - - this.x = Math.floor(this.x); - this.y = Math.floor(this.y); - this.width = Math.floor(this.width); - this.height = Math.floor(this.height); - - }, - - /** - * Copies the x, y, width and height properties from any given object to this Rectangle. - * @method Phaser.Rectangle#copyFrom - * @param {any} source - The object to copy from. - * @return {Rectangle} This Rectangle object. - **/ - copyFrom: function (source) { - return this.setTo(source.x, source.y, source.width, source.height); - }, - - /** - * Copies the x, y, width and height properties from this Rectangle to any given object. - * @method Phaser.Rectangle#copyTo - * @param {any} source - The object to copy to. - * @return {object} This object. - **/ - copyTo: function (dest) { - - dest.x = this.x; - dest.y = this.y; - dest.width = this.width; - dest.height = this.height; - - return dest; - - }, - - /** - * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. - * @method Phaser.Rectangle#inflate - * @param {number} dx - The amount to be added to the left side of the Rectangle. - * @param {number} dy - The amount to be added to the bottom side of the Rectangle. - * @return {Phaser.Rectangle} This Rectangle object. - */ - inflate: function (dx, dy) { - return Phaser.Rectangle.inflate(this, dx, dy); - }, - - /** - * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. - * @method Phaser.Rectangle#size - * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. - * @return {Phaser.Point} The size of the Rectangle object. - */ - size: function (output) { - return Phaser.Rectangle.size(this, output); - }, - - /** - * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. - * @method Phaser.Rectangle#clone - * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. - * @return {Phaser.Rectangle} - */ - clone: function (output) { - return Phaser.Rectangle.clone(this, output); - }, - - /** - * Determines whether the specified coordinates are contained within the region defined by this Rectangle object. - * @method Phaser.Rectangle#contains - * @param {number} x - The x coordinate of the point to test. - * @param {number} y - The y coordinate of the point to test. - * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - */ - contains: function (x, y) { - return Phaser.Rectangle.contains(this, x, y); - }, - - /** - * Determines whether the first Rectangle object is fully contained within the second Rectangle object. - * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. - * @method Phaser.Rectangle#containsRect - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. - */ - containsRect: function (b) { - return Phaser.Rectangle.containsRect(this, b); - }, - - /** - * Determines whether the two Rectangles are equal. - * This method compares the x, y, width and height properties of each Rectangle. - * @method Phaser.Rectangle#equals - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. - */ - equals: function (b) { - return Phaser.Rectangle.equals(this, b); - }, - - /** - * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. - * @method Phaser.Rectangle#intersection - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. - */ - intersection: function (b, out) { - return Phaser.Rectangle.intersection(this, b, output); - }, - - /** - * Determines whether the two Rectangles intersect with each other. - * This method checks the x, y, width, and height properties of the Rectangles. - * @method Phaser.Rectangle#intersects - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0. - * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. - */ - intersects: function (b, tolerance) { - return Phaser.Rectangle.intersects(this, b, tolerance); - }, - - /** - * Determines whether the object specified intersects (overlaps) with the given values. - * @method Phaser.Rectangle#intersectsRaw - * @param {number} left - Description. - * @param {number} right - Description. - * @param {number} top - Description. - * @param {number} bottomt - Description. - * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 - * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. - */ - intersectsRaw: function (left, right, top, bottom, tolerance) { - return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance); - }, - - /** - * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. - * @method Phaser.Rectangle#union - * @param {Phaser.Rectangle} b - The second Rectangle object. - * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. - * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. - */ - union: function (b, out) { - return Phaser.Rectangle.union(this, b, out); - }, - - /** - * Returns a string representation of this object. - * @method Phaser.Rectangle#toString - * @return {string} A string representation of the instance. - **/ - toString: function () { - return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]"; - } - -}; - -/** -* @name Phaser.Rectangle#halfWidth -* @property {number} halfWidth - Half of the width of the Rectangle. -* @readonly -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", { - - get: function () { - return Math.round(this.width / 2); - } - -}); - -/** -* @name Phaser.Rectangle#halfHeight -* @property {number} halfHeight - Half of the height of the Rectangle. -* @readonly -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", { - - get: function () { - return Math.round(this.height / 2); - } - -}); - -/** -* The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. -* @name Phaser.Rectangle#bottom -* @property {number} bottom - The sum of the y and height properties. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "bottom", { - - get: function () { - return this.y + this.height; - }, - - set: function (value) { - if (value <= this.y) { - this.height = 0; - } else { - this.height = (this.y - value); - } - } - -}); - -/** -* The location of the Rectangles bottom right corner as a Point object. -* @name Phaser.Rectangle#bottom -* @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", { - - get: function () { - return new Phaser.Point(this.right, this.bottom); - }, - - set: function (value) { - this.right = value.x; - this.bottom = value.y; - } - -}); - -/** -* The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property. -* @name Phaser.Rectangle#left -* @property {number} left - The x coordinate of the left of the Rectangle. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "left", { - - get: function () { - return this.x; - }, - - set: function (value) { - if (value >= this.right) { - this.width = 0; - } else { - this.width = this.right - value; - } - this.x = value; - } - -}); - -/** -* The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property. -* @name Phaser.Rectangle#right -* @property {number} right - The sum of the x and width properties. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "right", { - - get: function () { - return this.x + this.width; - }, - - set: function (value) { - if (value <= this.x) { - this.width = 0; - } else { - this.width = this.x + value; - } - } - -}); - -/** -* The volume of the Rectangle derived from width * height. -* @name Phaser.Rectangle#volume -* @property {number} volume - The volume of the Rectangle derived from width * height. -* @readonly -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "volume", { - - get: function () { - return this.width * this.height; - } - -}); - -/** -* The perimeter size of the Rectangle. This is the sum of all 4 sides. -* @name Phaser.Rectangle#perimeter -* @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides. -* @readonly -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", { - - get: function () { - return (this.width * 2) + (this.height * 2); - } - -}); - -/** -* The x coordinate of the center of the Rectangle. -* @name Phaser.Rectangle#centerX -* @property {number} centerX - The x coordinate of the center of the Rectangle. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "centerX", { - - get: function () { - return this.x + this.halfWidth; - }, - - set: function (value) { - this.x = value - this.halfWidth; - } - -}); - -/** -* The y coordinate of the center of the Rectangle. -* @name Phaser.Rectangle#centerY -* @property {number} centerY - The y coordinate of the center of the Rectangle. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "centerY", { - - get: function () { - return this.y + this.halfHeight; - }, - - set: function (value) { - this.y = value - this.halfHeight; - } - -}); - -/** -* The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties. -* However it does affect the height property, whereas changing the y value does not affect the height property. -* @name Phaser.Rectangle#top -* @property {number} top - The y coordinate of the top of the Rectangle. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "top", { - - get: function () { - return this.y; - }, - - set: function (value) { - if (value >= this.bottom) { - this.height = 0; - this.y = value; - } else { - this.height = (this.bottom - value); - } - } - -}); - -/** -* The location of the Rectangles top left corner as a Point object. -* @name Phaser.Rectangle#topLeft -* @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", { - - get: function () { - return new Phaser.Point(this.x, this.y); - }, - - set: function (value) { - this.x = value.x; - this.y = value.y; - } - -}); - -/** -* Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0. -* If set to true then all of the Rectangle properties are set to 0. -* @name Phaser.Rectangle#empty -* @property {boolean} empty - Gets or sets the Rectangles empty state. -*/ -Object.defineProperty(Phaser.Rectangle.prototype, "empty", { - - get: function () { - return (!this.width || !this.height); - }, - - set: function (value) { - this.setTo(0, 0, 0, 0); - } - -}); - -/** -* Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value. -* @method Phaser.Rectangle.inflate -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {number} dx - The amount to be added to the left side of the Rectangle. -* @param {number} dy - The amount to be added to the bottom side of the Rectangle. -* @return {Phaser.Rectangle} This Rectangle object. -*/ -Phaser.Rectangle.inflate = function (a, dx, dy) { - a.x -= dx; - a.width += 2 * dx; - a.y -= dy; - a.height += 2 * dy; - return a; -}; - -/** -* Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter. -* @method Phaser.Rectangle.inflatePoint -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object. -* @return {Phaser.Rectangle} The Rectangle object. -*/ -Phaser.Rectangle.inflatePoint = function (a, point) { - return Phaser.Rectangle.inflate(a, point.x, point.y); -}; - -/** -* The size of the Rectangle object, expressed as a Point object with the values of the width and height properties. -* @method Phaser.Rectangle.size -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned. -* @return {Phaser.Point} The size of the Rectangle object -*/ -Phaser.Rectangle.size = function (a, output) { - if (typeof output === "undefined") { output = new Phaser.Point(); } - return output.setTo(a.width, a.height); -}; - -/** -* Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object. -* @method Phaser.Rectangle.clone -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} -*/ -Phaser.Rectangle.clone = function (a, output) { - if (typeof output === "undefined") { output = new Phaser.Rectangle(); } - return output.setTo(a.x, a.y, a.width, a.height); -}; - -/** -* Determines whether the specified coordinates are contained within the region defined by this Rectangle object. -* @method Phaser.Rectangle.contains -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {number} x - The x coordinate of the point to test. -* @param {number} y - The y coordinate of the point to test. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ -Phaser.Rectangle.contains = function (a, x, y) { - return (x >= a.x && x <= a.right && y >= a.y && y <= a.bottom); -}; - -Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) { - return (x >= rx && x <= (rx + rw) && y >= ry && y <= (ry + rh)); -}; - -/** -* Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter. -* @method Phaser.Rectangle.containsPoint -* @param {Phaser.Rectangle} a - The Rectangle object. -* @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ -Phaser.Rectangle.containsPoint = function (a, point) { - return Phaser.Rectangle.contains(a, point.x, point.y); -}; - -/** -* Determines whether the first Rectangle object is fully contained within the second Rectangle object. -* A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first. -* @method Phaser.Rectangle.containsRect -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false. -*/ -Phaser.Rectangle.containsRect = function (a, b) { - - // If the given rect has a larger volume than this one then it can never contain it - if (a.volume > b.volume) - { - return false; - } - - return (a.x >= b.x && a.y >= b.y && a.right <= b.right && a.bottom <= b.bottom); - -}; - -/** -* Determines whether the two Rectangles are equal. -* This method compares the x, y, width and height properties of each Rectangle. -* @method Phaser.Rectangle.equals -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false. -*/ -Phaser.Rectangle.equals = function (a, b) { - return (a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height); -}; - -/** -* If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0. -* @method Phaser.Rectangle.intersection -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0. -*/ -Phaser.Rectangle.intersection = function (a, b, out) { - - out = out || new Phaser.Rectangle; - - if (Phaser.Rectangle.intersects(a, b)) - { - out.x = Math.max(a.x, b.x); - out.y = Math.max(a.y, b.y); - out.width = Math.min(a.right, b.right) - out.x; - out.height = Math.min(a.bottom, b.bottom) - out.y; - } - - return out; - -}; - -/** -* Determines whether the two Rectangles intersect with each other. -* This method checks the x, y, width, and height properties of the Rectangles. -* @method Phaser.Rectangle.intersects -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false. -*/ -Phaser.Rectangle.intersects = function (a, b) { - - return (a.x < b.right && b.x < a.right && a.y < b.bottom && b.y < a.bottom); - - // return (a.x <= b.right && b.x <= a.right && a.y <= b.bottom && b.y <= a.bottom); - - // return (a.left <= b.right && b.left <= a.right && a.top <= b.bottom && b.top <= a.bottom); - // return !(a.x > b.right + tolerance || a.right < b.x - tolerance || a.y > b.bottom + tolerance || a.bottom < b.y - tolerance); - -}; - -/** -* Determines whether the object specified intersects (overlaps) with the given values. -* @method Phaser.Rectangle.intersectsRaw -* @param {number} left - Description. -* @param {number} right - Description. -* @param {number} top - Description. -* @param {number} bottom - Description. -* @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0 -* @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false. -*/ -Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) { - - if (typeof tolerance === "undefined") { tolerance = 0; } - - return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance); - -}; - -/** -* Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles. -* @method Phaser.Rectangle.union -* @param {Phaser.Rectangle} a - The first Rectangle object. -* @param {Phaser.Rectangle} b - The second Rectangle object. -* @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned. -* @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles. -*/ -Phaser.Rectangle.union = function (a, b, out) { - - if (typeof out === "undefined") { out = new Phaser.Rectangle(); } - - return out.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top)); - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Creates a new Polygon. You have to provide a list of points. -* This can be an array of Points that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], -* or the arguments passed can be all the points of the polygon e.g. `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the -* arguments passed can be flat x,y values e.g. `new PIXI.Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are numbers. -* -* @class Phaser.Polygon -* @classdesc The polygon represents a list of orderded points in space -* @constructor -* @param {Array|Array} points - The array of Points. -*/ -Phaser.Polygon = function (points) { - - PIXI.Polygon.call(this, points); - - /** - * @property {number} type - The base object type. - */ - this.type = Phaser.POLYGON; - -}; - -Phaser.Polygon.prototype = Object.create(PIXI.Polygon.prototype); -Phaser.Polygon.prototype.constructor = Phaser.Polygon; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Description of Phaser.Net -* -* @class Phaser.Net -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Net = function (game) { - - this.game = game; - -}; - -Phaser.Net.prototype = { - - /** - * Returns the hostname given by the browser. - * - * @method Phaser.Net#getHostName - * @return {string} - */ - getHostName: function () { - - if (window.location && window.location.hostname) { - return window.location.hostname; - } - - return null; - - }, - - /** - * Compares the given domain name against the hostname of the browser containing the game. - * If the domain name is found it returns true. - * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc. - * Do not include 'http://' at the start. - * - * @method Phaser.Net#checkDomainName - * @param {string} domain - * @return {boolean} - */ - checkDomainName: function (domain) { - return window.location.hostname.indexOf(domain) !== -1; - }, - - /** - * Updates a value on the Query String and returns it in full. - * If the value doesn't already exist it is set. - * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string. - * Optionally you can redirect to the new url, or just return it as a string. - * - * @method Phaser.Net#updateQueryString - * @param {string} key - The querystring key to update. - * @param {string} value - The new value to be set. If it already exists it will be replaced. - * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring. - * @param {string} url - The URL to modify. If none is given it uses window.location.href. - * @return {string} If redirect is false then the modified url and query string is returned. - */ - updateQueryString: function (key, value, redirect, url) { - - if (typeof redirect === "undefined") { redirect = false; } - if (typeof url === "undefined") { url = ''; } - - if (url == '') { - url = window.location.href; - } - - var output = ''; - var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi"); - - if (re.test(url)) - { - if (typeof value !== 'undefined' && value !== null) - { - output = url.replace(re, '$1' + key + "=" + value + '$2$3'); - } - else - { - output = url.replace(re, '$1$3').replace(/(&|\?)$/, ''); - } - } - else - { - if (typeof value !== 'undefined' && value !== null) - { - var separator = url.indexOf('?') !== -1 ? '&' : '?'; - var hash = url.split('#'); - url = hash[0] + separator + key + '=' + value; - - if (hash[1]) { - url += '#' + hash[1]; - } - - output = url; - - } - else - { - output = url; - } - } - - if (redirect) - { - window.location.href = output; - } - else - { - return output; - } - - }, - - /** - * Returns the Query String as an object. - * If you specify a parameter it will return just the value of that parameter, should it exist. - * - * @method Phaser.Net#getQueryString - * @param {string} [parameter=''] - If specified this will return just the value for that key. - * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given. - */ - getQueryString: function (parameter) { - - if (typeof parameter === "undefined") { parameter = ''; } - - var output = {}; - var keyValues = location.search.substring(1).split('&'); - - for (var i in keyValues) { - - var key = keyValues[i].split('='); - - if (key.length > 1) - { - if (parameter && parameter == this.decodeURI(key[0])) - { - return this.decodeURI(key[1]); - } - else - { - output[this.decodeURI(key[0])] = this.decodeURI(key[1]); - } - } - } - - return output; - - }, - - /** - * Returns the Query String as an object. - * If you specify a parameter it will return just the value of that parameter, should it exist. - * - * @method Phaser.Net#decodeURI - * @param {string} value - The URI component to be decoded. - * @return {string} The decoded value. - */ - decodeURI: function (value) { - return decodeURIComponent(value.replace(/\+/g, " ")); - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser - TweenManager -* -* @class Phaser.TweenManager -* @classdesc -* Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated. -* Tweens are hooked into the game clock and pause system, adjusting based on the game state. -* -* TweenManager is based heavily on tween.js by http://soledadpenades.com. -* The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object. -* It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors. -* Please see https://github.com/sole/tween.js for a full list of contributors. -* @constructor -* -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.TweenManager = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {array} _tweens - Description. - * @private - */ - this._tweens = []; - - /** - * @property {array} _add - Description. - * @private - */ - this._add = []; - - this.game.onPause.add(this.pauseAll, this); - this.game.onResume.add(this.resumeAll, this); - -}; - -Phaser.TweenManager.prototype = { - - /** - * Version number of this library. - * @property {string} REVISION - * @default - */ - REVISION: '11dev', - - /** - * Get all the tween objects in an array. - * @method Phaser.TweenManager#getAll - * @returns {Phaser.Tween[]} Array with all tween objects. - */ - getAll: function () { - - return this._tweens; - - }, - - /** - * Remove all tween objects. - * @method Phaser.TweenManager#removeAll - */ - removeAll: function () { - - this._tweens = []; - - }, - - /** - * Add a new tween into the TweenManager. - * - * @method Phaser.TweenManager#add - * @param {Phaser.Tween} tween - The tween object you want to add. - * @returns {Phaser.Tween} The tween object you added to the manager. - */ - add: function ( tween ) { - - this._add.push( tween ); - - }, - - /** - * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite. - * - * @method Phaser.TweenManager#create - * @param {Object} object - Object the tween will be run on. - * @returns {Phaser.Tween} The newly created tween object. - */ - create: function (object) { - - return new Phaser.Tween(object, this.game); - - }, - - /** - * Remove a tween from this manager. - * - * @method Phaser.TweenManager#remove - * @param {Phaser.Tween} tween - The tween object you want to remove. - */ - remove: function ( tween ) { - - var i = this._tweens.indexOf( tween ); - - if ( i !== -1 ) { - - this._tweens[i].pendingDelete = true; - - } - - }, - - /** - * Update all the tween objects you added to this manager. - * - * @method Phaser.TweenManager#update - * @returns {boolean} Return false if there's no tween to update, otherwise return true. - */ - update: function () { - - if ( this._tweens.length === 0 && this._add.length === 0 ) return false; - - var i = 0; - var numTweens = this._tweens.length; - - while ( i < numTweens ) { - - if ( this._tweens[ i ].update( this.game.time.now ) ) { - - i++; - - } else { - - this._tweens.splice( i, 1 ); - - numTweens--; - - } - - } - - // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running - if (this._add.length > 0) - { - this._tweens = this._tweens.concat(this._add); - this._add.length = 0; - } - - return true; - - }, - - /** - * Checks to see if a particular Sprite is currently being tweened. - * - * @method Phaser.TweenManager#isTweening - * @param {object} object - The object to check for tweens against. - * @returns {boolean} Returns true if the object is currently being tweened, false if not. - */ - isTweening: function(object) { - - return this._tweens.some(function(tween) { - return tween._object === object; - }); - - }, - - /** - * Pauses all currently running tweens. - * - * @method Phaser.TweenManager#update - */ - pauseAll: function () { - - for (var i = this._tweens.length - 1; i >= 0; i--) { - this._tweens[i].pause(); - }; - - }, - - /** - * Pauses all currently paused tweens. - * - * @method Phaser.TweenManager#resumeAll - */ - resumeAll: function () { - - for (var i = this._tweens.length - 1; i >= 0; i--) { - this._tweens[i].resume(); - }; - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Tween constructor -* Create a new Tween. -* -* @class Phaser.Tween -* @constructor -* @param {object} object - Target object will be affected by this tween. -* @param {Phaser.Game} game - Current game instance. -*/ -Phaser.Tween = function (object, game) { - - /** - * Reference to the target object. - * @property {object} _object - * @private - */ - this._object = object; - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {object} _manager - Description. - * @private - */ - this._manager = this.game.tweens; - - /** - * @property {object} _valuesStart - Description. - * @private - */ - this._valuesStart = {}; - - /** - * @property {object} _valuesEnd - Description. - * @private - */ - this._valuesEnd = {}; - - /** - * @property {object} _valuesStartRepeat - Description. - * @private - */ - this._valuesStartRepeat = {}; - - /** - * @property {number} _duration - Description. - * @private - * @default - */ - this._duration = 1000; - - /** - * @property {number} _repeat - Description. - * @private - * @default - */ - this._repeat = 0; - - /** - * @property {boolean} _yoyo - Description. - * @private - * @default - */ - this._yoyo = false; - - /** - * @property {boolean} _reversed - Description. - * @private - * @default - */ - this._reversed = false; - - /** - * @property {number} _delayTime - Description. - * @private - * @default - */ - this._delayTime = 0; - - /** - * @property {Description} _startTime - Description. - * @private - * @default null - */ - this._startTime = null; - - /** - * @property {Description} _easingFunction - Description. - * @private - */ - this._easingFunction = Phaser.Easing.Linear.None; - - /** - * @property {Description} _interpolationFunction - Description. - * @private - */ - this._interpolationFunction = Phaser.Math.linearInterpolation; - - /** - * @property {Description} _chainedTweens - Description. - * @private - */ - this._chainedTweens = []; - - /** - * @property {Description} _onStartCallback - Description. - * @private - * @default - */ - this._onStartCallback = null; - - /** - * @property {boolean} _onStartCallbackFired - Description. - * @private - * @default - */ - this._onStartCallbackFired = false; - - /** - * @property {Description} _onUpdateCallback - Description. - * @private - * @default null - */ - this._onUpdateCallback = null; - - /** - * @property {Description} _onCompleteCallback - Description. - * @private - * @default null - */ - this._onCompleteCallback = null; - - /** - * @property {number} _pausedTime - Description. - * @private - * @default - */ - this._pausedTime = 0; - - /** - * @property {boolean} pendingDelete - If this tween is ready to be deleted by the TweenManager. - * @default - */ - this.pendingDelete = false; - - // Set all starting values present on the target object - for ( var field in object ) { - this._valuesStart[ field ] = parseFloat(object[field], 10); - } - - /** - * @property {Phaser.Signal} onStart - Description. - */ - this.onStart = new Phaser.Signal(); - - /** - * @property {Phaser.Signal} onComplete - Description. - */ - this.onComplete = new Phaser.Signal(); - - /** - * @property {boolean} isRunning - Description. - * @default - */ - this.isRunning = false; - -}; - -Phaser.Tween.prototype = { - - /** - * Configure the Tween - * - * @method Phaser.Tween#to - * @param {object} properties - Properties you want to tween. - * @param {number} duration - Duration of this tween. - * @param {function} ease - Easing function. - * @param {boolean} autoStart - Whether this tween will start automatically or not. - * @param {number} delay - Delay before this tween will start, defaults to 0 (no delay). - * @param {boolean} repeat - Should the tween automatically restart once complete? (ignores any chained tweens). - * @param {Phaser.Tween} yoyo - Description. - * @return {Phaser.Tween} Itself. - */ - to: function ( properties, duration, ease, autoStart, delay, repeat, yoyo ) { - - duration = duration || 1000; - ease = ease || null; - autoStart = autoStart || false; - delay = delay || 0; - repeat = repeat || 0; - yoyo = yoyo || false; - - var self; - if (this._parent) - { - self = this._manager.create(this._object); - this._lastChild.chain(self); - this._lastChild = self; - } - else - { - self = this; - this._parent = this; - this._lastChild = this; - } - - self._repeat = repeat; - self._duration = duration; - self._valuesEnd = properties; - - if (ease !== null) - { - self._easingFunction = ease; - } - - if (delay > 0) - { - self._delayTime = delay; - } - - self._yoyo = yoyo; - - if (autoStart) { - return this.start(); - } else { - return this; - } - - }, - - /** - * Starts the tween running. Can also be called by the autoStart parameter of Tween.to. - * - * @method Phaser.Tween#start - * @param {number} time - Description. - * @return {Phaser.Tween} Itself. - */ - start: function ( time ) { - - if (this.game === null || this._object === null) { - return; - } - - this._manager.add(this); - - this.onStart.dispatch(this._object); - - this.isRunning = true; - - this._onStartCallbackFired = false; - - this._startTime = this.game.time.now + this._delayTime; - - for ( var property in this._valuesEnd ) { - - // check if an Array was provided as property value - if ( this._valuesEnd[ property ] instanceof Array ) { - - if ( this._valuesEnd[ property ].length === 0 ) { - - continue; - - } - - // create a local copy of the Array with the start value at the front - this._valuesEnd[ property ] = [ this._object[ property ] ].concat( this._valuesEnd[ property ] ); - - } - - this._valuesStart[ property ] = this._object[ property ]; - - if ( ( this._valuesStart[ property ] instanceof Array ) === false ) { - this._valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings - } - - this._valuesStartRepeat[ property ] = this._valuesStart[ property ] || 0; - - } - - return this; - - }, - - /** - * Stops the tween if running and removes it from the TweenManager. If there are any onComplete callbacks or events they are not dispatched. - * - * @method Phaser.Tween#stop - * @return {Phaser.Tween} Itself. - */ - stop: function () { - - this.isRunning = false; - - this._manager.remove(this); - - return this; - - }, - - /** - * Sets a delay time before this tween will start. - * - * @method Phaser.Tween#delay - * @param {number} amount - The amount of the delay in ms. - * @return {Phaser.Tween} Itself. - */ - delay: function ( amount ) { - - this._delayTime = amount; - return this; - - }, - - /** - * Sets the number of times this tween will repeat. - * - * @method Phaser.Tween#repeat - * @param {number} times - How many times to repeat. - * @return {Phaser.Tween} Itself. - */ - repeat: function ( times ) { - - this._repeat = times; - return this; - - }, - - /** - * A tween that has yoyo set to true will run through from start to finish, then reverse from finish to start. - * Used in combination with repeat you can create endless loops. - * - * @method Phaser.Tween#yoyo - * @param {boolean} yoyo - Set to true to yoyo this tween. - * @return {Phaser.Tween} Itself. - */ - yoyo: function( yoyo ) { - - this._yoyo = yoyo; - return this; - - }, - - /** - * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None. - * - * @method Phaser.Tween#easing - * @param {function} easing - The easing function this tween will use, i.e. Phaser.Easing.Linear.None. - * @return {Phaser.Tween} Itself. - */ - easing: function ( easing ) { - - this._easingFunction = easing; - return this; - - }, - - /** - * Set interpolation function the tween will use, by default it uses Phaser.Math.linearInterpolation. - * - * @method Phaser.Tween#interpolation - * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default) - * @return {Phaser.Tween} Itself. - */ - interpolation: function ( interpolation ) { - - this._interpolationFunction = interpolation; - return this; - - }, - - /** - * You can chain tweens together by passing a reference to the chain function. This enables one tween to call another on completion. - * You can pass as many tweens as you like to this function, they will each be chained in sequence. - * - * @method Phaser.Tween#chain - * @return {Phaser.Tween} Itself. - */ - chain: function () { - - this._chainedTweens = arguments; - return this; - - }, - - /** - * Loop a chain of tweens - * - * Usage: - * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true) - * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None) - * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None) - * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None) - * .loop(); - * @method Phaser.Tween#loop - * @return {Phaser.Tween} Itself. - */ - loop: function() { - - this._lastChild.chain(this); - return this; - - }, - - /** - * Sets a callback to be fired when the tween starts. Note: callback will be called in the context of the global scope. - * - * @method Phaser.Tween#onStartCallback - * @param {function} callback - The callback to invoke on start. - * @return {Phaser.Tween} Itself. - */ - onStartCallback: function ( callback ) { - - this._onStartCallback = callback; - return this; - - }, - - /** - * Sets a callback to be fired each time this tween updates. Note: callback will be called in the context of the global scope. - * - * @method Phaser.Tween#onUpdateCallback - * @param {function} callback - The callback to invoke each time this tween is updated. - * @return {Phaser.Tween} Itself. - */ - onUpdateCallback: function ( callback ) { - - this._onUpdateCallback = callback; - return this; - - }, - - /** - * Sets a callback to be fired when the tween completes. Note: callback will be called in the context of the global scope. - * - * @method Phaser.Tween#onCompleteCallback - * @param {function} callback - The callback to invoke on completion. - * @return {Phaser.Tween} Itself. - */ - onCompleteCallback: function ( callback ) { - - this._onCompleteCallback = callback; - return this; - - }, - - /** - * Pauses the tween. - * - * @method Phaser.Tween#pause - */ - pause: function () { - this._paused = true; - this._pausedTime = this.game.time.now; - }, - - /** - * Resumes a paused tween. - * - * @method Phaser.Tween#resume - */ - resume: function () { - this._paused = false; - this._startTime += (this.game.time.now - this._pausedTime); - }, - - /** - * Core tween update function called by the TweenManager. Does not need to be invoked directly. - * - * @method Phaser.Tween#update - * @param {number} time - A timestamp passed in by the TweenManager. - * @return {boolean} false if the tween has completed and should be deleted from the manager, otherwise true (still active). - */ - update: function ( time ) { - - if (this.pendingDelete) - { - return false; - } - - if (this._paused || time < this._startTime) { - - return true; - - } - - var property; - - if ( time < this._startTime ) { - - return true; - - } - - if ( this._onStartCallbackFired === false ) { - - if ( this._onStartCallback !== null ) { - - this._onStartCallback.call( this._object ); - - } - - this._onStartCallbackFired = true; - - } - - var elapsed = ( time - this._startTime ) / this._duration; - elapsed = elapsed > 1 ? 1 : elapsed; - - var value = this._easingFunction( elapsed ); - - for ( property in this._valuesEnd ) { - - var start = this._valuesStart[ property ] || 0; - var end = this._valuesEnd[ property ]; - - if ( end instanceof Array ) { - - this._object[ property ] = this._interpolationFunction( end, value ); - - } else { - - // Parses relative end values with start as base (e.g.: +10, -3) - if ( typeof(end) === "string" ) { - end = start + parseFloat(end, 10); - } - - // protect against non numeric properties. - if ( typeof(end) === "number" ) { - this._object[ property ] = start + ( end - start ) * value; - } - - } - - } - - if ( this._onUpdateCallback !== null ) { - - this._onUpdateCallback.call( this._object, value ); - - } - - if ( elapsed == 1 ) { - - if ( this._repeat > 0 ) { - - if ( isFinite( this._repeat ) ) { - this._repeat--; - } - - // reassign starting values, restart by making startTime = now - for ( property in this._valuesStartRepeat ) { - - if ( typeof( this._valuesEnd[ property ] ) === "string" ) { - this._valuesStartRepeat[ property ] = this._valuesStartRepeat[ property ] + parseFloat(this._valuesEnd[ property ], 10); - } - - if (this._yoyo) { - var tmp = this._valuesStartRepeat[ property ]; - this._valuesStartRepeat[ property ] = this._valuesEnd[ property ]; - this._valuesEnd[ property ] = tmp; - this._reversed = !this._reversed; - } - this._valuesStart[ property ] = this._valuesStartRepeat[ property ]; - - } - - this._startTime = time + this._delayTime; - - this.onComplete.dispatch(this._object); - - if ( this._onCompleteCallback !== null ) { - this._onCompleteCallback.call( this._object ); - } - - return true; - - } else { - - this.onComplete.dispatch(this._object); - - if ( this._onCompleteCallback !== null ) { - this._onCompleteCallback.call( this._object ); - } - - for ( var i = 0, numChainedTweens = this._chainedTweens.length; i < numChainedTweens; i ++ ) { - - this._chainedTweens[ i ].start( time ); - - } - - return false; - - } - - } - - return true; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A collection of easing methods defining ease-in ease-out curves. -* -* @class Phaser.Easing -*/ -Phaser.Easing = { - - /** - * Linear easing. - * - * @class Phaser.Easing.Linear - */ - Linear: { - - /** - * Ease-in. - * - * @method Phaser.Easing.Linear#In - * @param {number} k - The value to be tweened. - * @returns {number} k^2. - */ - None: function ( k ) { - - return k; - - } - - }, - - /** - * Quadratic easing. - * - * @class Phaser.Easing.Quadratic - */ - Quadratic: { - - /** - * Ease-in. - * - * @method Phaser.Easing.Quadratic#In - * @param {number} k - The value to be tweened. - * @returns {number} k^2. - */ - In: function ( k ) { - - return k * k; - - }, - - /** - * Ease-out. - * - * @method Phaser.Easing.Quadratic#Out - * @param {number} k - The value to be tweened. - * @returns {number} k* (2-k). - */ - Out: function ( k ) { - - return k * ( 2 - k ); - - }, - - /** - * Ease-in/out. - * - * @method Phaser.Easing.Quadratic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1 ) return 0.5 * k * k; - return - 0.5 * ( --k * ( k - 2 ) - 1 ); - - } - - }, - - /** - * Cubic easing. - * - * @class Phaser.Easing.Cubic - */ - Cubic: { - - /** - * Cubic ease-in. - * - * @method Phaser.Easing.Cubic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return k * k * k; - - }, - - /** - * Cubic ease-out. - * - * @method Phaser.Easing.Cubic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return --k * k * k + 1; - - }, - - /** - * Cubic ease-in/out. - * - * @method Phaser.Easing.Cubic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k; - return 0.5 * ( ( k -= 2 ) * k * k + 2 ); - - } - - }, - - /** - * Quartic easing. - * - * @class Phaser.Easing.Quartic - */ - Quartic: { - - /** - * Quartic ease-in. - * - * @method Phaser.Easing.Quartic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return k * k * k * k; - - }, - - /** - * Quartic ease-out. - * - * @method Phaser.Easing.Quartic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return 1 - ( --k * k * k * k ); - - }, - - /** - * Quartic ease-in/out. - * - * @method Phaser.Easing.Quartic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k; - return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 ); - - } - - }, - - /** - * Quintic easing. - * - * @class Phaser.Easing.Quintic - */ - Quintic: { - - /** - * Quintic ease-in. - * - * @method Phaser.Easing.Quintic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return k * k * k * k * k; - - }, - - /** - * Quintic ease-out. - * - * @method Phaser.Easing.Quintic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return --k * k * k * k * k + 1; - - }, - - /** - * Quintic ease-in/out. - * - * @method Phaser.Easing.Quintic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k; - return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 ); - - } - - }, - - /** - * Sinusoidal easing. - * - * @class Phaser.Easing.Sinusoidal - */ - Sinusoidal: { - - /** - * Sinusoidal ease-in. - * - * @method Phaser.Easing.Sinusoidal#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return 1 - Math.cos( k * Math.PI / 2 ); - - }, - - /** - * Sinusoidal ease-out. - * - * @method Phaser.Easing.Sinusoidal#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return Math.sin( k * Math.PI / 2 ); - - }, - - /** - * Sinusoidal ease-in/out. - * - * @method Phaser.Easing.Sinusoidal#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - return 0.5 * ( 1 - Math.cos( Math.PI * k ) ); - - } - - }, - - /** - * Exponential easing. - * - * @class Phaser.Easing.Exponential - */ - Exponential: { - - /** - * Exponential ease-in. - * - * @method Phaser.Easing.Exponential#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return k === 0 ? 0 : Math.pow( 1024, k - 1 ); - - }, - - /** - * Exponential ease-out. - * - * @method Phaser.Easing.Exponential#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k ); - - }, - - /** - * Exponential ease-in/out. - * - * @method Phaser.Easing.Exponential#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 ); - return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 ); - - } - - }, - - /** - * Circular easing. - * - * @class Phaser.Easing.Circular - */ - Circular: { - - /** - * Circular ease-in. - * - * @method Phaser.Easing.Circular#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return 1 - Math.sqrt( 1 - k * k ); - - }, - - /** - * Circular ease-out. - * - * @method Phaser.Easing.Circular#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - return Math.sqrt( 1 - ( --k * k ) ); - - }, - - /** - * Circular ease-in/out. - * - * @method Phaser.Easing.Circular#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1); - return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1); - - } - - }, - - /** - * Elastic easing. - * - * @class Phaser.Easing.Elastic - */ - Elastic: { - - /** - * Elastic ease-in. - * - * @method Phaser.Easing.Elastic#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); - - }, - - /** - * Elastic ease-out. - * - * @method Phaser.Easing.Elastic#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 ); - - }, - - /** - * Elastic ease-in/out. - * - * @method Phaser.Easing.Elastic#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - var s, a = 0.1, p = 0.4; - if ( k === 0 ) return 0; - if ( k === 1 ) return 1; - if ( !a || a < 1 ) { a = 1; s = p / 4; } - else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI ); - if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) ); - return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1; - - } - - }, - - /** - * Back easing. - * - * @class Phaser.Easing.Back - */ - Back: { - - /** - * Back ease-in. - * - * @method Phaser.Easing.Back#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - var s = 1.70158; - return k * k * ( ( s + 1 ) * k - s ); - - }, - - /** - * Back ease-out. - * - * @method Phaser.Easing.Back#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - var s = 1.70158; - return --k * k * ( ( s + 1 ) * k + s ) + 1; - - }, - - /** - * Back ease-in/out. - * - * @method Phaser.Easing.Back#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - var s = 1.70158 * 1.525; - if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) ); - return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 ); - - } - - }, - - /** - * Bounce easing. - * - * @class Phaser.Easing.Bounce - */ - Bounce: { - - /** - * Bounce ease-in. - * - * @method Phaser.Easing.Bounce#In - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - In: function ( k ) { - - return 1 - Phaser.Easing.Bounce.Out( 1 - k ); - - }, - - /** - * Bounce ease-out. - * - * @method Phaser.Easing.Bounce#Out - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - Out: function ( k ) { - - if ( k < ( 1 / 2.75 ) ) { - - return 7.5625 * k * k; - - } else if ( k < ( 2 / 2.75 ) ) { - - return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75; - - } else if ( k < ( 2.5 / 2.75 ) ) { - - return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375; - - } else { - - return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375; - - } - - }, - - /** - * Bounce ease-in/out. - * - * @method Phaser.Easing.Bounce#InOut - * @param {number} k - The value to be tweened. - * @returns {number} The tweened value. - */ - InOut: function ( k ) { - - if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5; - return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5; - - } - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Time constructor. -* -* @class Phaser.Time -* @classdesc This is the core internal game clock. It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens. -* @constructor -* @param {Phaser.Game} game A reference to the currently running game. -*/ -Phaser.Time = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * The time at which the Game instance started. - * @property {number} _started - * @private - * @default - */ - this._started = 0; - - /** - * The time (in ms) that the last second counter ticked over. - * @property {number} _timeLastSecond - * @private - * @default - */ - this._timeLastSecond = 0; - - /** - * The time the game started being paused. - * @property {number} _pauseStarted - * @private - * @default - */ - this._pauseStarted = 0; - - /** - * The elapsed time calculated for the physics motion updates. - * @property {number} physicsElapsed - * @default - */ - this.physicsElapsed = 0; - - /** - * Game time counter. - * @property {number} time - * @default - */ - this.time = 0; - - /** - * Records how long the game has been paused for. Is reset each time the game pauses. - * @property {number} pausedTime - * @default - */ - this.pausedTime = 0; - - /** - * The time right now. - * @property {number} now - * @default - */ - this.now = 0; - - /** - * Elapsed time since the last frame. - * @property {number} elapsed - * @default - */ - this.elapsed = 0; - - /** - * Frames per second. - * @property {number} fps - * @default - */ - this.fps = 0; - - /** - * The lowest rate the fps has dropped to. - * @property {number} fpsMin - * @default - */ - this.fpsMin = 1000; - - /** - * The highest rate the fps has reached (usually no higher than 60fps). - * @property {number} fpsMax - * @default - */ - this.fpsMax = 0; - - /** - * The minimum amount of time the game has taken between two frames. - * @property {number} msMin - * @default - */ - this.msMin = 1000; - - /** - * The maximum amount of time the game has taken between two frames. - * @property {number} msMax - * @default - */ - this.msMax = 0; - - /** - * The number of frames record in the last second. - * @property {number} frames - * @default - */ - this.frames = 0; - - /** - * Records how long the game was paused for in miliseconds. - * @property {number} pauseDuration - * @default - */ - this.pauseDuration = 0; - - /** - * The value that setTimeout needs to work out when to next update - * @property {number} timeToCall - * @default - */ - this.timeToCall = 0; - - /** - * Internal value used by timeToCall as part of the setTimeout loop - * @property {number} lastTime - * @default - */ - this.lastTime = 0; - - // Listen for game pause/resume events - this.game.onPause.add(this.gamePaused, this); - this.game.onResume.add(this.gameResumed, this); - - /** - * Description. - * @property {boolean} _justResumed - * @default - */ - this._justResumed = false; - -}; - -Phaser.Time.prototype = { - - /** - * The number of seconds that have elapsed since the game was started. - * @method Phaser.Time#totalElapsedSeconds - * @return {number} - */ - totalElapsedSeconds: function() { - return (this.now - this._started) * 0.001; - }, - - /** - * Updates the game clock and calculate the fps. This is called automatically by Phaser.Game. - * @method Phaser.Time#update - * @param {number} time - The current timestamp, either performance.now or Date.now depending on the browser. - */ - update: function (time) { - - this.now = time; - - if (this._justResumed) - { - this.time = this.now; - this._justResumed = false; - } - - this.timeToCall = this.game.math.max(0, 16 - (time - this.lastTime)); - - this.elapsed = this.now - this.time; - - this.msMin = this.game.math.min(this.msMin, this.elapsed); - this.msMax = this.game.math.max(this.msMax, this.elapsed); - - this.frames++; - - if (this.now > this._timeLastSecond + 1000) - { - this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond)); - this.fpsMin = this.game.math.min(this.fpsMin, this.fps); - this.fpsMax = this.game.math.max(this.fpsMax, this.fps); - this._timeLastSecond = this.now; - this.frames = 0; - } - - this.time = this.now; - this.lastTime = time + this.timeToCall; - this.physicsElapsed = 1.0 * (this.elapsed / 1000); - - // Clamp the delta - if (this.physicsElapsed > 1) - { - this.physicsElapsed = 1; - } - - // Paused? - if (this.game.paused) - { - this.pausedTime = this.now - this._pauseStarted; - } - - }, - - /** - * Called when the game enters a paused state. - * @method Phaser.Time#gamePaused - * @private - */ - gamePaused: function () { - - this._pauseStarted = this.now; - - }, - - /** - * Called when the game resumes from a paused state. - * @method Phaser.Time#gameResumed - * @private - */ - gameResumed: function () { - - // Level out the elapsed timer to avoid spikes - this.time = Date.now(); - this.pauseDuration = this.pausedTime; - this._justResumed = true; - - }, - - /** - * How long has passed since the given time. - * @method Phaser.Time#elapsedSince - * @param {number} since - The time you want to measure against. - * @return {number} The difference between the given time and now. - */ - elapsedSince: function (since) { - return this.now - since; - }, - - /** - * How long has passed since the given time (in seconds). - * @method Phaser.Time#elapsedSecondsSince - * @param {number} since - The time you want to measure (in seconds). - * @return {number} Duration between given time and now (in seconds). - */ - elapsedSecondsSince: function (since) { - return (this.now - since) * 0.001; - }, - - /** - * Resets the private _started value to now. - * @method Phaser.Time#reset - */ - reset: function () { - this._started = this.now; - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Animation Manager is used to add, play and update Phaser Animations. -* Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance. -* -* @class Phaser.AnimationManager -* @constructor -* @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager. -*/ -Phaser.AnimationManager = function (sprite) { - - /** - * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager. - */ - this.sprite = sprite; - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = sprite.game; - - /** - * @property {Phaser.Frame} currentFrame - The currently displayed Frame of animation, if any. - * @default - */ - this.currentFrame = null; - - /** - * @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false. - * @default - */ - this.updateIfVisible = true; - - /** - * @property {boolean} isLoaded - Set to true once animation data has been loaded. - * @default - */ - this.isLoaded = false; - - /** - * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData. - * @private - * @default - */ - this._frameData = null; - - /** - * @property {object} _anims - An internal object that stores all of the Animation instances. - * @private - */ - this._anims = {}; - - /** - * @property {object} _outputFrames - An internal object to help avoid gc. - * @private - */ - this._outputFrames = []; - -}; - -Phaser.AnimationManager.prototype = { - - /** - * Loads FrameData into the internal temporary vars and resets the frame index to zero. - * This is called automatically when a new Sprite is created. - * - * @method Phaser.AnimationManager#loadFrameData - * @private - * @param {Phaser.FrameData} frameData - The FrameData set to load. - */ - loadFrameData: function (frameData) { - - this._frameData = frameData; - this.frame = 0; - this.isLoaded = true; - - }, - - /** - * Adds a new animation under the given key. Optionally set the frames, frame rate and loop. - * Animations added in this way are played back with the play function. - * - * @method Phaser.AnimationManager#add - * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk". - * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used. - * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second. - * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once. - * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? - * @return {Phaser.Animation} The Animation object that was created. - */ - add: function (name, frames, frameRate, loop, useNumericIndex) { - - if (this._frameData == null) - { - console.warn('No FrameData available for Phaser.Animation ' + name); - return; - } - - frameRate = frameRate || 60; - - if (typeof loop === 'undefined') { loop = false; } - - // If they didn't set the useNumericIndex then let's at least try and guess it - if (typeof useNumericIndex === 'undefined') - { - if (frames && typeof frames[0] === 'number') - { - useNumericIndex = true; - } - else - { - useNumericIndex = false; - } - } - - // Create the signals the AnimationManager will emit - if (this.sprite.events.onAnimationStart == null) - { - this.sprite.events.onAnimationStart = new Phaser.Signal(); - this.sprite.events.onAnimationComplete = new Phaser.Signal(); - this.sprite.events.onAnimationLoop = new Phaser.Signal(); - } - - this._outputFrames.length = 0; - - this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames); - - this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop); - this.currentAnim = this._anims[name]; - this.currentFrame = this.currentAnim.currentFrame; - this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - - return this._anims[name]; - - }, - - /** - * Check whether the frames in the given array are valid and exist. - * - * @method Phaser.AnimationManager#validateFrames - * @param {Array} frames - An array of frames to be validated. - * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false) - * @return {boolean} True if all given Frames are valid, otherwise false. - */ - validateFrames: function (frames, useNumericIndex) { - - if (typeof useNumericIndex == 'undefined') { useNumericIndex = true; } - - for (var i = 0; i < frames.length; i++) - { - if (useNumericIndex == true) - { - if (frames[i] > this._frameData.total) - { - return false; - } - } - else - { - if (this._frameData.checkFrameName(frames[i]) == false) - { - return false; - } - } - } - - return true; - - }, - - /** - * Play an animation based on the given key. The animation should previously have been added via sprite.animations.add() - * If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself. - * - * @method Phaser.AnimationManager#play - * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". - * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. - * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. - * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. - * @return {Phaser.Animation} A reference to playing Animation instance. - */ - play: function (name, frameRate, loop, killOnComplete) { - - if (this._anims[name]) - { - if (this.currentAnim == this._anims[name]) - { - if (this.currentAnim.isPlaying == false) - { - this.currentAnim.paused = false; - return this.currentAnim.play(frameRate, loop, killOnComplete); - } - } - else - { - this.currentAnim = this._anims[name]; - this.currentAnim.paused = false; - return this.currentAnim.play(frameRate, loop, killOnComplete); - } - } - - }, - - /** - * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped. - * The currentAnim property of the AnimationManager is automatically set to the animation given. - * - * @method Phaser.AnimationManager#stop - * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped. - * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false) - */ - stop: function (name, resetFrame) { - - if (typeof resetFrame == 'undefined') { resetFrame = false; } - - if (typeof name == 'string') - { - if (this._anims[name]) - { - this.currentAnim = this._anims[name]; - this.currentAnim.stop(resetFrame); - } - } - else - { - if (this.currentAnim) - { - this.currentAnim.stop(resetFrame); - } - } - - }, - - /** - * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events. - * - * @method Phaser.AnimationManager#update - * @protected - * @return {boolean} True if a new animation frame has been set, otherwise false. - */ - update: function () { - - if (this.updateIfVisible && this.sprite.visible == false) - { - return false; - } - - if (this.currentAnim && this.currentAnim.update() == true) - { - this.currentFrame = this.currentAnim.currentFrame; - this.sprite.currentFrame = this.currentFrame; - return true; - } - - return false; - - }, - - /** - * Returns an animation that was previously added by name. - * - * @method Phaser.AnimationManager#getAnimation - * @param {string} name - The name of the animation to be returned, e.g. "fire". - * @return {Phaser.Animation|boolean} The Animation instance, if found, otherwise false. - */ - getAnimation: function (name) { - - if (typeof name == 'string') - { - if (this._anims[name]) - { - return this._anims[name]; - } - } - - return false; - - }, - - /** - * Refreshes the current frame data back to the parent Sprite and also resets the texture data. - * - * @method Phaser.AnimationManager#refreshFrame - */ - refreshFrame: function () { - - this.sprite.currentFrame = this.currentFrame; - this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - - }, - - /** - * Destroys all references this AnimationManager contains. Sets the _anims to a new object and nulls the current animation. - * - * @method Phaser.AnimationManager#destroy - */ - destroy: function () { - - this._anims = {}; - this._frameData = null; - this._frameIndex = 0; - this.currentAnim = null; - this.currentFrame = null; - - } - -}; - -/** -* @name Phaser.AnimationManager#frameData -* @property {Phaser.FrameData} frameData - The current animations FrameData. -* @readonly -*/ -Object.defineProperty(Phaser.AnimationManager.prototype, "frameData", { - - get: function () { - return this._frameData; - } - -}); - -/** -* @name Phaser.AnimationManager#frameTotal -* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. -* @readonly -*/ -Object.defineProperty(Phaser.AnimationManager.prototype, "frameTotal", { - - get: function () { - - if (this._frameData) - { - return this._frameData.total; - } - else - { - return -1; - } - } - -}); - -/** -* @name Phaser.AnimationManager#paused -* @property {boolean} paused - Gets and sets the paused state of the current animation. -*/ -Object.defineProperty(Phaser.AnimationManager.prototype, "paused", { - - get: function () { - - return this.currentAnim.isPaused; - - }, - - set: function (value) { - - this.currentAnim.paused = value; - - } - -}); - -/** -* @name Phaser.AnimationManager#frame -* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. -*/ -Object.defineProperty(Phaser.AnimationManager.prototype, "frame", { - - get: function () { - - if (this.currentFrame) - { - return this._frameIndex; - } - - }, - - set: function (value) { - - if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null) - { - this.currentFrame = this._frameData.getFrame(value); - this._frameIndex = value; - this.sprite.currentFrame = this.currentFrame; - this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - } - - } - -}); - -/** -* @name Phaser.AnimationManager#frameName -* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display. -*/ -Object.defineProperty(Phaser.AnimationManager.prototype, "frameName", { - - get: function () { - - if (this.currentFrame) - { - return this.currentFrame.name; - } - - }, - - set: function (value) { - - if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null) - { - this.currentFrame = this._frameData.getFrameByName(value); - this._frameIndex = this.currentFrame.index; - this.sprite.currentFrame = this.currentFrame; - this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - } - else - { - console.warn("Cannot set frameName: " + value); - } - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* An Animation instance contains a single animation and the controls to play it. -* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite. -* -* @class Phaser.Animation -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Phaser.Sprite} parent - A reference to the owner of this Animation. -* @param {string} name - The unique name for this animation, used in playback commands. -* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation. -* @param {(Array.|Array.)} frames - An array of numbers or strings indicating which frames to play in which order. -* @param {number} delay - The time between each frame of the animation, given in ms. -* @param {boolean} looped - Should this animation loop or play through once. -*/ -Phaser.Animation = function (game, parent, name, frameData, frames, delay, looped) { - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation. - * @private - */ - this._parent = parent; - - /** - * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses. - * @private - */ - this._frameData = frameData; - - /** - * @property {string} name - The user defined name given to this Animation. - */ - this.name = name; - - /** - * @property {object} _frames - * @private - */ - this._frames = []; - this._frames = this._frames.concat(frames); - - /** - * @property {number} delay - The delay in ms between each frame of the Animation. - */ - this.delay = 1000 / delay; - - /** - * @property {boolean} looped - The loop state of the Animation. - */ - this.looped = looped; - - /** - * @property {boolean} looped - The loop state of the Animation. - */ - this.killOnComplete = false; - - /** - * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback. - * @default - */ - this.isFinished = false; - - /** - * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback. - * @default - */ - this.isPlaying = false; - - /** - * @property {boolean} isPaused - The paused state of the Animation. - * @default - */ - this.isPaused = false; - - /** - * @property {boolean} _pauseStartTime - The time the animation paused. - * @private - * @default - */ - this._pauseStartTime = 0; - - /** - * @property {number} _frameIndex - * @private - * @default - */ - this._frameIndex = 0; - - /** - * @property {number} _frameDiff - * @private - * @default - */ - this._frameDiff = 0; - - /** - * @property {number} _frameSkip - * @private - * @default - */ - this._frameSkip = 1; - - /** - * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation. - */ - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); - -}; - -Phaser.Animation.prototype = { - - /** - * Plays this animation. - * - * @method Phaser.Animation#play - * @memberof Phaser.Animation - * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used. - * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used. - * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed. - * @return {Phaser.Animation} - A reference to this Animation instance. - */ - play: function (frameRate, loop, killOnComplete) { - - if (typeof frameRate === 'number') - { - // If they set a new frame rate then use it, otherwise use the one set on creation - this.delay = 1000 / frameRate; - } - - if (typeof loop === 'boolean') - { - // If they set a new loop value then use it, otherwise use the one set on creation - this.looped = loop; - } - - if (typeof killOnComplete !== 'undefined') - { - // Remove the parent sprite once the animation has finished? - this.killOnComplete = killOnComplete; - } - - this.isPlaying = true; - this.isFinished = false; - this.paused = false; - - this._timeLastFrame = this.game.time.now; - this._timeNextFrame = this.game.time.now + this.delay; - - this._frameIndex = 0; - - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); - this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - - if (this._parent.events) - { - this._parent.events.onAnimationStart.dispatch(this._parent, this); - } - - return this; - - }, - - /** - * Sets this animation back to the first frame and restarts the animation. - * - * @method Phaser.Animation#restart - * @memberof Phaser.Animation - */ - restart: function () { - - this.isPlaying = true; - this.isFinished = false; - this.paused = false; - - this._timeLastFrame = this.game.time.now; - this._timeNextFrame = this.game.time.now + this.delay; - - this._frameIndex = 0; - - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); - - }, - - /** - * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation. - * - * @method Phaser.Animation#stop - * @memberof Phaser.Animation - * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation. - */ - stop: function (resetFrame) { - - if (typeof resetFrame === 'undefined') { resetFrame = false; } - - this.isPlaying = false; - this.isFinished = true; - this.paused = false; - - if (resetFrame) - { - this.currentFrame = this._frameData.getFrame(this._frames[0]); - } - - }, - - /** - * Updates this animation. Called automatically by the AnimationManager. - * - * @method Phaser.Animation#update - * @memberof Phaser.Animation - */ - update: function () { - - if (this.isPaused) - { - return false; - } - - if (this.isPlaying == true && this.game.time.now >= this._timeNextFrame) - { - this._frameSkip = 1; - - // Lagging? - this._frameDiff = this.game.time.now - this._timeNextFrame; - - this._timeLastFrame = this.game.time.now; - - if (this._frameDiff > this.delay) - { - // We need to skip a frame, work out how many - this._frameSkip = Math.floor(this._frameDiff / this.delay); - - this._frameDiff -= (this._frameSkip * this.delay); - } - - // And what's left now? - this._timeNextFrame = this.game.time.now + (this.delay - this._frameDiff); - - this._frameIndex += this._frameSkip; - - if (this._frameIndex >= this._frames.length) - { - if (this.looped) - { - this._frameIndex %= this._frames.length; - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); - - if (this.currentFrame) - { - this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - } - - this._parent.events.onAnimationLoop.dispatch(this._parent, this); - } - else - { - this.onComplete(); - } - } - else - { - this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]); - - if (this.currentFrame) - { - this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - } - } - - return true; - } - - return false; - - }, - - /** - * Cleans up this animation ready for deletion. Nulls all values and references. - * - * @method Phaser.Animation#destroy - * @memberof Phaser.Animation - */ - destroy: function () { - - this.game = null; - this._parent = null; - this._frames = null; - this._frameData = null; - this.currentFrame = null; - this.isPlaying = false; - - }, - - /** - * Called internally when the animation finishes playback. Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent. - * - * @method Phaser.Animation#onComplete - * @memberof Phaser.Animation - */ - onComplete: function () { - - this.isPlaying = false; - this.isFinished = true; - this.paused = false; - - if (this._parent.events) - { - this._parent.events.onAnimationComplete.dispatch(this._parent, this); - } - - if (this.killOnComplete) - { - this._parent.kill(); - } - - } - -}; - -/** -* @name Phaser.Animation#paused -* @property {boolean} paused - Gets and sets the paused state of this Animation. -*/ -Object.defineProperty(Phaser.Animation.prototype, "paused", { - - get: function () { - - return this.isPaused; - - }, - - set: function (value) { - - this.isPaused = value; - - if (value) - { - // Paused - this._pauseStartTime = this.game.time.now; - } - else - { - // Un-paused - if (this.isPlaying) - { - this._timeNextFrame = this.game.time.now + this.delay; - } - } - - } - -}); - -/** -* @name Phaser.Animation#frameTotal -* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded. -* @readonly -*/ -Object.defineProperty(Phaser.Animation.prototype, "frameTotal", { - - get: function () { - return this._frames.length; - } - -}); - -/** -* @name Phaser.Animation#frame -* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display. -*/ -Object.defineProperty(Phaser.Animation.prototype, "frame", { - - get: function () { - - if (this.currentFrame !== null) - { - return this.currentFrame.index; - } - else - { - return this._frameIndex; - } - - }, - - set: function (value) { - - this.currentFrame = this._frameData.getFrame(value); - - if (this.currentFrame !== null) - { - this._frameIndex = value; - this._parent.setTexture(PIXI.TextureCache[this.currentFrame.uuid]); - } - - } - -}); - -/** -* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers. -* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large' -* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4); -* -* @method Phaser.Animation.generateFrameNames -* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'. -* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1. -* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34. -* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'. -* @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4. -*/ -Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) { - - if (typeof suffix == 'undefined') { suffix = ''; } - - var output = []; - var frame = ''; - - if (start < stop) - { - for (var i = start; i <= stop; i++) - { - if (typeof zeroPad == 'number') - { - // str, len, pad, dir - frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); - } - else - { - frame = i.toString(); - } - - frame = prefix + frame + suffix; - - output.push(frame); - } - } - else - { - for (var i = start; i >= stop; i--) - { - if (typeof zeroPad == 'number') - { - // str, len, pad, dir - frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1); - } - else - { - frame = i.toString(); - } - - frame = prefix + frame + suffix; - - output.push(frame); - } - } - - return output; - -} - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A Frame is a single frame of an animation and is part of a FrameData collection. -* -* @class Phaser.Frame -* @constructor -* @param {number} index - The index of this Frame within the FrameData set it is being added to. -* @param {number} x - X position of the frame within the texture image. -* @param {number} y - Y position of the frame within the texture image. -* @param {number} width - Width of the frame within the texture image. -* @param {number} height - Height of the frame within the texture image. -* @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename. -* @param {string} uuid - Internal UUID key. -*/ -Phaser.Frame = function (index, x, y, width, height, name, uuid) { - - /** - * @property {number} index - The index of this Frame within the FrameData set it is being added to. - */ - this.index = index; - - /** - * @property {number} x - X position within the image to cut from. - */ - this.x = x; - - /** - * @property {number} y - Y position within the image to cut from. - */ - this.y = y; - - /** - * @property {number} width - Width of the frame. - */ - this.width = width; - - /** - * @property {number} height - Height of the frame. - */ - this.height = height; - - /** - * @property {string} name - Useful for Texture Atlas files (is set to the filename value). - */ - this.name = name; - - /** - * @property {string} uuid - A link to the PIXI.TextureCache entry. - */ - this.uuid = uuid; - - /** - * @property {number} centerX - Center X position within the image to cut from. - */ - this.centerX = Math.floor(width / 2); - - /** - * @property {number} centerY - Center Y position within the image to cut from. - */ - this.centerY = Math.floor(height / 2); - - /** - * @property {number} distance - The distance from the top left to the bottom-right of this Frame. - */ - this.distance = Phaser.Math.distance(0, 0, width, height); - - /** - * @property {boolean} rotated - Rotated? (not yet implemented) - * @default - */ - this.rotated = false; - - /** - * @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees. - * @default 'cw' - */ - this.rotationDirection = 'cw'; - - /** - * @property {boolean} trimmed - Was it trimmed when packed? - * @default - */ - this.trimmed = false; - - /** - * @property {number} sourceSizeW - Width of the original sprite. - */ - this.sourceSizeW = width; - - /** - * @property {number} sourceSizeH - Height of the original sprite. - */ - this.sourceSizeH = height; - - /** - * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite. - * @default - */ - this.spriteSourceSizeX = 0; - - /** - * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite. - * @default - */ - this.spriteSourceSizeY = 0; - - /** - * @property {number} spriteSourceSizeW - Width of the trimmed sprite. - * @default - */ - this.spriteSourceSizeW = 0; - - /** - * @property {number} spriteSourceSizeH - Height of the trimmed sprite. - * @default - */ - this.spriteSourceSizeH = 0; - -}; - -Phaser.Frame.prototype = { - - /** - * If the frame was trimmed when added to the Texture Atlas this records the trim and source data. - * - * @method Phaser.Frame#setTrim - * @param {boolean} trimmed - If this frame was trimmed or not. - * @param {number} actualWidth - The width of the frame before being trimmed. - * @param {number} actualHeight - The height of the frame before being trimmed. - * @param {number} destX - The destination X position of the trimmed frame for display. - * @param {number} destY - The destination Y position of the trimmed frame for display. - * @param {number} destWidth - The destination width of the trimmed frame for display. - * @param {number} destHeight - The destination height of the trimmed frame for display. - */ - setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) { - - this.trimmed = trimmed; - - if (trimmed) - { - this.width = actualWidth; - this.height = actualHeight; - this.sourceSizeW = actualWidth; - this.sourceSizeH = actualHeight; - this.centerX = Math.floor(actualWidth / 2); - this.centerY = Math.floor(actualHeight / 2); - this.spriteSourceSizeX = destX; - this.spriteSourceSizeY = destY; - this.spriteSourceSizeW = destWidth; - this.spriteSourceSizeH = destHeight; - } - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser. -* -* @class Phaser.FrameData -* @constructor -*/ -Phaser.FrameData = function () { - - /** - * @property {Array} _frames - Local array of frames. - * @private - */ - this._frames = []; - - - /** - * @property {Array} _frameNames - Local array of frame names for name to index conversions. - * @private - */ - this._frameNames = []; - -}; - -Phaser.FrameData.prototype = { - - /** - * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly. - * - * @method Phaser.FrameData#addFrame - * @param {Phaser.Frame} frame - The frame to add to this FrameData set. - * @return {Phaser.Frame} The frame that was just added. - */ - addFrame: function (frame) { - - frame.index = this._frames.length; - - this._frames.push(frame); - - if (frame.name !== '') - { - this._frameNames[frame.name] = frame.index; - } - - return frame; - - }, - - /** - * Get a Frame by its numerical index. - * - * @method Phaser.FrameData#getFrame - * @param {number} index - The index of the frame you want to get. - * @return {Phaser.Frame} The frame, if found. - */ - getFrame: function (index) { - - if (this._frames.length > index) - { - return this._frames[index]; - } - - return null; - - }, - - /** - * Get a Frame by its frame name. - * - * @method Phaser.FrameData#getFrameByName - * @param {string} name - The name of the frame you want to get. - * @return {Phaser.Frame} The frame, if found. - */ - getFrameByName: function (name) { - - if (typeof this._frameNames[name] === 'number') - { - return this._frames[this._frameNames[name]]; - } - - return null; - - }, - - /** - * Check if there is a Frame with the given name. - * - * @method Phaser.FrameData#checkFrameName - * @param {string} name - The name of the frame you want to check. - * @return {boolean} True if the frame is found, otherwise false. - */ - checkFrameName: function (name) { - - if (this._frameNames[name] == null) - { - return false; - } - - return true; - - }, - - /** - * Returns a range of frames based on the given start and end frame indexes and returns them in an Array. - * - * @method Phaser.FrameData#getFrameRange - * @param {number} start - The starting frame index. - * @param {number} end - The ending frame index. - * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. - * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found. - */ - getFrameRange: function (start, end, output) { - - if (typeof output === "undefined") { output = []; } - - for (var i = start; i <= end; i++) - { - output.push(this._frames[i]); - } - - return output; - - }, - - /** - * Returns all of the Frames in this FrameData set where the frame index is found in the input array. - * The frames are returned in the output array, or if none is provided in a new Array object. - * - * @method Phaser.FrameData#getFrames - * @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned. - * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) - * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. - * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs. - */ - getFrames: function (frames, useNumericIndex, output) { - - if (typeof useNumericIndex === "undefined") { useNumericIndex = true; } - if (typeof output === "undefined") { output = []; } - - if (typeof frames === "undefined" || frames.length == 0) - { - // No input array, so we loop through all frames - for (var i = 0; i < this._frames.length; i++) - { - // We only need the indexes - output.push(this._frames[i]); - } - } - else - { - // Input array given, loop through that instead - for (var i = 0, len = frames.length; i < len; i++) - { - // Does the input array contain names or indexes? - if (useNumericIndex) - { - // The actual frame - output.push(this.getFrame(frames[i])); - } - else - { - // The actual frame - output.push(this.getFrameByName(frames[i])); - } - } - } - - return output; - - }, - - /** - * Returns all of the Frame indexes in this FrameData set. - * The frames indexes are returned in the output array, or if none is provided in a new Array object. - * - * @method Phaser.FrameData#getFrameIndexes - * @param {Array} frames - An Array containing the indexes of the frames to retrieve. If the array is empty then all frames in the FrameData are returned. - * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false) - * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created. - * @return {Array} An array of all Frame indexes matching the given names or IDs. - */ - getFrameIndexes: function (frames, useNumericIndex, output) { - - if (typeof useNumericIndex === "undefined") { useNumericIndex = true; } - if (typeof output === "undefined") { output = []; } - - if (typeof frames === "undefined" || frames.length == 0) - { - // No frames array, so we loop through all frames - for (var i = 0, len = this._frames.length; i < len; i++) - { - output.push(this._frames[i].index); - } - } - else - { - // Input array given, loop through that instead - for (var i = 0, len = frames.length; i < len; i++) - { - // Does the frames array contain names or indexes? - if (useNumericIndex) - { - output.push(frames[i]); - } - else - { - if (this.getFrameByName(frames[i])) - { - output.push(this.getFrameByName(frames[i]).index); - } - } - } - } - - return output; - - } - -}; - -/** -* @name Phaser.FrameData#total -* @property {number} total - The total number of frames in this FrameData set. -* @readonly -*/ -Object.defineProperty(Phaser.FrameData.prototype, "total", { - - get: function () { - return this._frames.length; - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations. -* -* @class Phaser.AnimationParser -*/ -Phaser.AnimationParser = { - - /** - * Parse a Sprite Sheet and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.spriteSheet - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {string} key - The Game.Cache asset key of the Sprite Sheet image. - * @param {number} frameWidth - The fixed width of each frame of the animation. - * @param {number} frameHeight - The fixed height of each frame of the animation. - * @param {number} [frameMax=-1] - The total number of animation frames to extact from the Sprite Sheet. The default value of -1 means "extract all frames". - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ - spriteSheet: function (game, key, frameWidth, frameHeight, frameMax) { - - // How big is our image? - var img = game.cache.getImage(key); - - if (img == null) - { - return null; - } - - var width = img.width; - var height = img.height; - - if (frameWidth <= 0) - { - frameWidth = Math.floor(-width / Math.min(-1, frameWidth)); - } - - if (frameHeight <= 0) - { - frameHeight = Math.floor(-height / Math.min(-1, frameHeight)); - } - - var row = Math.round(width / frameWidth); - var column = Math.round(height / frameHeight); - var total = row * column; - - if (frameMax !== -1) - { - total = frameMax; - } - - // Zero or smaller than frame sizes? - if (width == 0 || height == 0 || width < frameWidth || height < frameHeight || total === 0) - { - console.warn("Phaser.AnimationParser.spriteSheet: width/height zero or width/height < given frameWidth/frameHeight"); - return null; - } - - // Let's create some frames then - var data = new Phaser.FrameData(); - var x = 0; - var y = 0; - - for (var i = 0; i < total; i++) - { - var uuid = game.rnd.uuid(); - - data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, '', uuid)); - - PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[key], { - x: x, - y: y, - width: frameWidth, - height: frameHeight - }); - - x += frameWidth; - - if (x === width) - { - x = 0; - y += frameHeight; - } - } - - return data; - - }, - - /** - * Parse the JSON data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.JSONData - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {Object} json - The JSON data from the Texture Atlas. Must be in Array format. - * @param {string} cacheKey - The Game.Cache asset key of the texture image. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ - JSONData: function (game, json, cacheKey) { - - // Malformed? - if (!json['frames']) - { - console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"); - console.log(json); - return; - } - - // Let's create some frames then - var data = new Phaser.FrameData(); - - // By this stage frames is a fully parsed array - var frames = json['frames']; - var newFrame; - - for (var i = 0; i < frames.length; i++) - { - var uuid = game.rnd.uuid(); - - newFrame = data.addFrame(new Phaser.Frame( - i, - frames[i].frame.x, - frames[i].frame.y, - frames[i].frame.w, - frames[i].frame.h, - frames[i].filename, - uuid - )); - - PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], { - x: frames[i].frame.x, - y: frames[i].frame.y, - width: frames[i].frame.w, - height: frames[i].frame.h - }); - - if (frames[i].trimmed) - { - newFrame.setTrim( - frames[i].trimmed, - frames[i].sourceSize.w, - frames[i].sourceSize.h, - frames[i].spriteSourceSize.x, - frames[i].spriteSourceSize.y, - frames[i].spriteSourceSize.w, - frames[i].spriteSourceSize.h - ); - - // We had to hack Pixi to get this to work :( - PIXI.TextureCache[uuid].trimmed = true; - PIXI.TextureCache[uuid].trim.x = frames[i].spriteSourceSize.x; - PIXI.TextureCache[uuid].trim.y = frames[i].spriteSourceSize.y; - - } - } - - return data; - - }, - - /** - * Parse the JSON data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.JSONDataHash - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {Object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format. - * @param {string} cacheKey - The Game.Cache asset key of the texture image. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ - JSONDataHash: function (game, json, cacheKey) { - - // Malformed? - if (!json['frames']) - { - console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"); - console.log(json); - return; - } - - // Let's create some frames then - var data = new Phaser.FrameData(); - - // By this stage frames is a fully parsed array - var frames = json['frames']; - var newFrame; - var i = 0; - - for (var key in frames) - { - var uuid = game.rnd.uuid(); - - newFrame = data.addFrame(new Phaser.Frame( - i, - frames[key].frame.x, - frames[key].frame.y, - frames[key].frame.w, - frames[key].frame.h, - key, - uuid - )); - - PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], { - x: frames[key].frame.x, - y: frames[key].frame.y, - width: frames[key].frame.w, - height: frames[key].frame.h - }); - - if (frames[key].trimmed) - { - newFrame.setTrim( - frames[key].trimmed, - frames[key].sourceSize.w, - frames[key].sourceSize.h, - frames[key].spriteSourceSize.x, - frames[key].spriteSourceSize.y, - frames[key].spriteSourceSize.w, - frames[key].spriteSourceSize.h - ); - - // We had to hack Pixi to get this to work :( - PIXI.TextureCache[uuid].trimmed = true; - PIXI.TextureCache[uuid].trim.x = frames[key].spriteSourceSize.x; - PIXI.TextureCache[uuid].trim.y = frames[key].spriteSourceSize.y; - - } - - i++; - } - - return data; - - }, - - /** - * Parse the XML data and extract the animation frame data from it. - * - * @method Phaser.AnimationParser.XMLData - * @param {Phaser.Game} game - A reference to the currently running game. - * @param {Object} xml - The XML data from the Texture Atlas. Must be in Starling XML format. - * @param {string} cacheKey - The Game.Cache asset key of the texture image. - * @return {Phaser.FrameData} A FrameData object containing the parsed frames. - */ - XMLData: function (game, xml, cacheKey) { - - // Malformed? - if (!xml.getElementsByTagName('TextureAtlas')) - { - console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing tag"); - return; - } - - // Let's create some frames then - var data = new Phaser.FrameData(); - var frames = xml.getElementsByTagName('SubTexture'); - var newFrame; - - var uuid; - var frame; - var x; - var y; - var width; - var height; - var frameX; - var frameY; - var frameWidth; - var frameHeight; - - for (var i = 0; i < frames.length; i++) - { - uuid = game.rnd.uuid(); - - frame = frames[i].attributes; - - name = frame.name.nodeValue; - x = parseInt(frame.x.nodeValue); - y = parseInt(frame.y.nodeValue); - width = parseInt(frame.width.nodeValue); - height = parseInt(frame.height.nodeValue); - - frameX = null; - frameY = null; - - if (frame.frameX) - { - frameX = Math.abs(parseInt(frame.frameX.nodeValue)); - frameY = Math.abs(parseInt(frame.frameY.nodeValue)); - frameWidth = parseInt(frame.frameWidth.nodeValue); - frameHeight = parseInt(frame.frameHeight.nodeValue); - } - - newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name, uuid)); - - PIXI.TextureCache[uuid] = new PIXI.Texture(PIXI.BaseTextureCache[cacheKey], { - x: x, - y: y, - width: width, - height: height - }); - - // Trimmed? - if (frameX !== null || frameY !== null) - { - newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight); - - PIXI.TextureCache[uuid].realSize = { x: frameX, y: frameY, w: frameWidth, h: frameHeight }; - - // We had to hack Pixi to get this to work :( - PIXI.TextureCache[uuid].trimmed = true; - PIXI.TextureCache[uuid].trim.x = frameX; - PIXI.TextureCache[uuid].trim.y = frameY; - } - } - - return data; - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser.Cache constructor. -* -* @class Phaser.Cache -* @classdesc A game only has one instance of a Cache and it is used to store all externally loaded assets such -* as images, sounds and data files as a result of Loader calls. Cache items use string based keys for look-up. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Cache = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {object} game - Canvas key-value container. - * @private - */ - this._canvases = {}; - - /** - * @property {object} _images - Image key-value container. - * @private - */ - this._images = {}; - - /** - * @property {object} _textures - RenderTexture key-value container. - * @private - */ - this._textures = {}; - - /** - * @property {object} _sounds - Sound key-value container. - * @private - */ - this._sounds = {}; - - /** - * @property {object} _text - Text key-value container. - * @private - */ - this._text = {}; - - /** - * @property {object} _tilemaps - Tilemap key-value container. - * @private - */ - this._tilemaps = {}; - - /** - * @property {object} _tilesets - Tileset key-value container. - * @private - */ - this._tilesets = {}; - - /** - * @property {object} _bitmapDatas - BitmapData key-value container. - * @private - */ - this._bitmapDatas = {}; - - this.addDefaultImage(); - this.addMissingImage(); - - /** - * @property {Phaser.Signal} onSoundUnlock - Description. - */ - this.onSoundUnlock = new Phaser.Signal; - -}; - -Phaser.Cache.prototype = { - - /** - * Add a new canvas object in to the cache. - * @method Phaser.Cache#addCanvas - * @param {string} key - Asset key for this canvas. - * @param {HTMLCanvasElement} canvas - Canvas DOM element. - * @param {CanvasRenderingContext2D} context - Render context of this canvas. - */ - addCanvas: function (key, canvas, context) { - - this._canvases[key] = { canvas: canvas, context: context }; - - }, - - /** - * Add a BitmapData object in to the cache. - * @method Phaser.Cache#addBitmapData - * @param {string} key - Asset key for this BitmapData. - * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache. - * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache. - */ - addBitmapData: function (key, bitmapData) { - - this._bitmapDatas[key] = bitmapData; - - return bitmapData; - - }, - - /** - * Add a new Phaser.RenderTexture in to the cache. - * - * @method Phaser.Cache#addRenderTexture - * @param {string} key - The unique key by which you will reference this object. - * @param {Phaser.Texture} texture - The texture to use as the base of the RenderTexture. - */ - addRenderTexture: function (key, texture) { - - var frame = new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', ''); - - this._textures[key] = { texture: texture, frame: frame }; - - }, - - /** - * Add a new sprite sheet in to the cache. - * - * @method Phaser.Cache#addSpriteSheet - * @param {string} key - The unique key by which you will reference this object. - * @param {string} url - URL of this sprite sheet file. - * @param {object} data - Extra sprite sheet data. - * @param {number} frameWidth - Width of the sprite sheet. - * @param {number} frameHeight - Height of the sprite sheet. - * @param {number} frameMax - How many frames stored in the sprite sheet. - */ - addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax) { - - this._images[key] = { url: url, data: data, spriteSheet: true, frameWidth: frameWidth, frameHeight: frameHeight }; - - PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data); - PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]); - - this._images[key].frameData = Phaser.AnimationParser.spriteSheet(this.game, key, frameWidth, frameHeight, frameMax); - - }, - - /** - * Add a new tile set in to the cache. - * - * @method Phaser.Cache#addTileset - * @param {string} key - The unique key by which you will reference this object. - * @param {string} url - URL of this tile set file. - * @param {object} data - Extra tile set data. - * @param {number} tileWidth - Width of the sprite sheet. - * @param {number} tileHeight - Height of the sprite sheet. - * @param {number} tileMax - How many tiles stored in the sprite sheet. - * @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here. - * @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here. - */ - addTileset: function (key, url, data, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { - - this._tilesets[key] = { url: url, data: data, tileWidth: tileWidth, tileHeight: tileHeight, tileMargin: tileMargin, tileSpacing: tileSpacing }; - - PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data); - PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]); - - this._tilesets[key].tileData = Phaser.TilemapParser.tileset(this.game, key, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing); - - }, - - /** - * Add a new tilemap. - * - * @method Phaser.Cache#addTilemap - * @param {string} key - The unique key by which you will reference this object. - * @param {string} url - URL of the tilemap image. - * @param {object} mapData - The tilemap data object. - * @param {number} format - The format of the tilemap data. - */ - addTilemap: function (key, url, mapData, format) { - - this._tilemaps[key] = { url: url, data: mapData, format: format }; - - this._tilemaps[key].layers = Phaser.TilemapParser.parse(this.game, mapData, format); - - }, - - /** - * Add a new texture atlas. - * - * @method Phaser.Cache#addTextureAtlas - * @param {string} key - The unique key by which you will reference this object. - * @param {string} url - URL of this texture atlas file. - * @param {object} data - Extra texture atlas data. - * @param {object} atlasData - Texture atlas frames data. - * @param {number} format - The format of the texture atlas. - */ - addTextureAtlas: function (key, url, data, atlasData, format) { - - this._images[key] = { url: url, data: data, spriteSheet: true }; - - PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data); - PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]); - - if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY) - { - this._images[key].frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key); - } - else if (format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH) - { - this._images[key].frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key); - } - else if (format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) - { - this._images[key].frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key); - } - - }, - - /** - * Add a new Bitmap Font. - * - * @method Phaser.Cache#addBitmapFont - * @param {string} key - The unique key by which you will reference this object. - * @param {string} url - URL of this font xml file. - * @param {object} data - Extra font data. - * @param xmlData {object} Texture atlas frames data. - */ - addBitmapFont: function (key, url, data, xmlData) { - - this._images[key] = { url: url, data: data, spriteSheet: true }; - - PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data); - PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]); - - Phaser.LoaderParser.bitmapFont(this.game, xmlData, key); - // this._images[key].frameData = Phaser.AnimationParser.XMLData(this.game, xmlData, key); - - }, - - /** - * Adds a default image to be used in special cases such as WebGL Filters. Is mapped to the key __default. - * - * @method Phaser.Cache#addDefaultImage - */ - addDefaultImage: function () { - - var img = new Image(); - img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg=="; - - this._images['__default'] = { url: null, data: img, spriteSheet: false }; - this._images['__default'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', ''); - - PIXI.BaseTextureCache['__default'] = new PIXI.BaseTexture(img); - PIXI.TextureCache['__default'] = new PIXI.Texture(PIXI.BaseTextureCache['__default']); - - }, - - /** - * Adds an image to be used when a key is wrong / missing. Is mapped to the key __missing. - * - * @method Phaser.Cache#addMissingImage - */ - addMissingImage: function () { - - var img = new Image(); - img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg=="; - - this._images['__missing'] = { url: null, data: img, spriteSheet: false }; - this._images['__missing'].frame = new Phaser.Frame(0, 0, 0, 32, 32, '', ''); - - PIXI.BaseTextureCache['__missing'] = new PIXI.BaseTexture(img); - PIXI.TextureCache['__missing'] = new PIXI.Texture(PIXI.BaseTextureCache['__missing']); - - }, - - /** - * Add a new text data. - * - * @method Phaser.Cache#addText - * @param {string} key - Asset key for the text data. - * @param {string} url - URL of this text data file. - * @param {object} data - Extra text data. - */ - addText: function (key, url, data) { - - this._text[key] = { - url: url, - data: data - }; - - }, - - /** - * Add a new image. - * - * @method Phaser.Cache#addImage - * @param {string} key - The unique key by which you will reference this object. - * @param {string} url - URL of this image file. - * @param {object} data - Extra image data. - */ - addImage: function (key, url, data) { - - this._images[key] = { url: url, data: data, spriteSheet: false }; - - this._images[key].frame = new Phaser.Frame(0, 0, 0, data.width, data.height, key, this.game.rnd.uuid()); - - PIXI.BaseTextureCache[key] = new PIXI.BaseTexture(data); - PIXI.TextureCache[key] = new PIXI.Texture(PIXI.BaseTextureCache[key]); - - }, - - /** - * Add a new sound. - * - * @method Phaser.Cache#addSound - * @param {string} key - Asset key for the sound. - * @param {string} url - URL of this sound file. - * @param {object} data - Extra sound data. - * @param {boolean} webAudio - True if the file is using web audio. - * @param {boolean} audioTag - True if the file is using legacy HTML audio. - */ - addSound: function (key, url, data, webAudio, audioTag) { - - webAudio = webAudio || true; - audioTag = audioTag || false; - - var locked = this.game.sound.touchLocked; - var decoded = false; - - if (audioTag) - { - decoded = true; - } - - this._sounds[key] = { url: url, data: data, isDecoding: false, decoded: decoded, webAudio: webAudio, audioTag: audioTag }; - - }, - - /** - * Reload a sound. - * @method Phaser.Cache#reloadSound - * @param {string} key - Asset key for the sound. - */ - reloadSound: function (key) { - - var _this = this; - - if (this._sounds[key]) - { - this._sounds[key].data.src = this._sounds[key].url; - - this._sounds[key].data.addEventListener('canplaythrough', function () { - return _this.reloadSoundComplete(key); - }, false); - - this._sounds[key].data.load(); - } - }, - - /** - * Description. - * @method Phaser.Cache#reloadSoundComplete - * @param {string} key - Asset key for the sound. - */ - reloadSoundComplete: function (key) { - - if (this._sounds[key]) - { - this._sounds[key].locked = false; - this.onSoundUnlock.dispatch(key); - } - - }, - - /** - * Description. - * @method Phaser.Cache#updateSound - * @param {string} key - Asset key for the sound. - */ - updateSound: function (key, property, value) { - - if (this._sounds[key]) - { - this._sounds[key][property] = value; - } - - }, - - /** - * Add a new decoded sound. - * - * @method Phaser.Cache#decodedSound - * @param {string} key - Asset key for the sound. - * @param {object} data - Extra sound data. - */ - decodedSound: function (key, data) { - - this._sounds[key].data = data; - this._sounds[key].decoded = true; - this._sounds[key].isDecoding = false; - - }, - - /** - * Get a canvas object from the cache by its key. - * - * @method Phaser.Cache#getCanvas - * @param {string} key - Asset key of the canvas you want. - * @return {object} The canvas you want. - */ - getCanvas: function (key) { - - if (this._canvases[key]) - { - return this._canvases[key].canvas; - } - - return null; - - }, - - /** - * Get a BitmapData object from the cache by its key. - * - * @method Phaser.Cache#getBitmapData - * @param {string} key - Asset key of the BitmapData object you want. - * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not. - */ - getBitmapData: function (key) { - - if (this._bitmapDatas[key]) - { - return this._bitmapDatas[key]; - } - - return null; - - }, - - /** - * Checks if an image key exists. - * - * @method Phaser.Cache#checkImageKey - * @param {string} key - Asset key of the image you want. - * @return {boolean} True if the key exists, otherwise false. - */ - checkImageKey: function (key) { - - if (this._images[key]) - { - return true; - } - - return false; - - }, - - /** - * Get image data by key. - * - * @method Phaser.Cache#getImage - * @param {string} key - Asset key of the image you want. - * @return {object} The image data you want. - */ - getImage: function (key) { - - if (this._images[key]) - { - return this._images[key].data; - } - - return null; - - }, - - /** - * Get tile set image data by key. - * - * @method Phaser.Cache#getTileSetImage - * @param {string} key - Asset key of the image you want. - * @return {object} The image data you want. - */ - getTilesetImage: function (key) { - - if (this._tilesets[key]) - { - return this._tilesets[key].data; - } - - return null; - - }, - - /** - * Get tile set image data by key. - * - * @method Phaser.Cache#getTileset - * @param {string} key - Asset key of the image you want. - * @return {Phaser.Tileset} The tileset data. The tileset image is in the data property, the tile data in tileData. - */ - getTileset: function (key) { - - if (this._tilesets[key]) - { - return this._tilesets[key].tileData; - } - - return null; - - }, - - /** - * Get tilemap data by key. - * - * @method Phaser.Cache#getTilemap - * @param {string} key - Asset key of the tilemap you want. - * @return {Object} The tilemap data. The tileset image is in the data property, the map data in mapData. - */ - getTilemapData: function (key) { - - if (this._tilemaps[key]) - { - return this._tilemaps[key]; - } - - return null; - }, - - /** - * Get frame data by key. - * - * @method Phaser.Cache#getFrameData - * @param {string} key - Asset key of the frame data you want. - * @return {Phaser.FrameData} The frame data you want. - */ - getFrameData: function (key) { - - if (this._images[key] && this._images[key].frameData) - { - return this._images[key].frameData; - } - - return null; - }, - - /** - * Get a single frame out of a frameData set by key. - * - * @method Phaser.Cache#getFrameByIndex - * @param {string} key - Asset key of the frame data you want. - * @return {Phaser.Frame} The frame data you want. - */ - getFrameByIndex: function (key, frame) { - - if (this._images[key] && this._images[key].frameData) - { - return this._images[key].frameData.getFrame(frame); - } - - return null; - }, - - /** - * Get a single frame out of a frameData set by key. - * - * @method Phaser.Cache#getFrameByName - * @param {string} key - Asset key of the frame data you want. - * @return {Phaser.Frame} The frame data you want. - */ - getFrameByName: function (key, frame) { - - if (this._images[key] && this._images[key].frameData) - { - return this._images[key].frameData.getFrameByName(frame); - } - - return null; - }, - - /** - * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. - * - * @method Phaser.Cache#getFrame - * @param {string} key - Asset key of the frame data you want. - * @return {Phaser.Frame} The frame data you want. - */ - getFrame: function (key) { - - if (this._images[key] && this._images[key].spriteSheet == false) - { - return this._images[key].frame; - } - - return null; - }, - - /** - * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image. - * - * @method Phaser.Cache#getTextureFrame - * @param {string} key - Asset key of the frame data you want. - * @return {Phaser.Frame} The frame data you want. - */ - getTextureFrame: function (key) { - - if (this._textures[key]) - { - return this._textures[key].frame; - } - - return null; - }, - - /** - * Get a RenderTexture by key. - * - * @method Phaser.Cache#getTexture - * @param {string} key - Asset key of the RenderTexture you want. - * @return {Phaser.RenderTexture} The RenderTexture you want. - */ - getTexture: function (key) { - - if (this._textures[key]) - { - return this._textures[key]; - } - - return null; - - }, - - /** - * Get sound by key. - * - * @method Phaser.Cache#getSound - * @param {string} key - Asset key of the sound you want. - * @return {Phaser.Sound} The sound you want. - */ - getSound: function (key) { - - if (this._sounds[key]) - { - return this._sounds[key]; - } - - return null; - - }, - - /** - * Get sound data by key. - * - * @method Phaser.Cache#getSoundData - * @param {string} key - Asset key of the sound you want. - * @return {object} The sound data you want. - */ - getSoundData: function (key) { - - if (this._sounds[key]) - { - return this._sounds[key].data; - } - - return null; - - }, - - /** - * Check if the given sound has finished decoding. - * - * @method Phaser.Cache#isSoundDecoded - * @param {string} key - Asset key of the sound you want. - * @return {boolean} The decoded state of the Sound object. - */ - isSoundDecoded: function (key) { - - if (this._sounds[key]) - { - return this._sounds[key].decoded; - } - - }, - - /** - * Check if the given sound is ready for playback. A sound is considered ready when it has finished decoding and the device is no longer touch locked. - * - * @method Phaser.Cache#isSoundReady - * @param {string} key - Asset key of the sound you want. - * @return {boolean} True if the sound is decoded and the device is not touch locked. - */ - isSoundReady: function (key) { - - return (this._sounds[key] && this._sounds[key].decoded && this.game.sound.touchLocked == false); - - }, - - /** - * Check whether an image asset is sprite sheet or not. - * - * @method Phaser.Cache#isSpriteSheet - * @param {string} key - Asset key of the sprite sheet you want. - * @return {boolean} True if the image is a sprite sheet. - */ - isSpriteSheet: function (key) { - - if (this._images[key]) - { - return this._images[key].spriteSheet; - } - - return false; - - }, - - /** - * Get text data by key. - * - * @method Phaser.Cache#getText - * @param {string} key - Asset key of the text data you want. - * @return {object} The text data you want. - */ - getText: function (key) { - - if (this._text[key]) - { - return this._text[key].data; - } - - return null; - - }, - - /** - * Get the cache keys from a given array of objects. - * Normally you don't call this directly but instead use getImageKeys, getSoundKeys, etc. - * - * @method Phaser.Cache#getKeys - * @param {Array} array - An array of items to return the keys for. - * @return {Array} The array of item keys. - */ - getKeys: function (array) { - - var output = []; - - for (var item in array) - { - if (item !== '__default') - { - output.push(item); - } - } - - return output; - - }, - - /** - * Returns an array containing all of the keys of Images in the Cache. - * - * @method Phaser.Cache#getImageKeys - * @return {Array} The string based keys in the Cache. - */ - getImageKeys: function () { - return this.getKeys(this._images); - }, - - /** - * Returns an array containing all of the keys of Sounds in the Cache. - * - * @method Phaser.Cache#getSoundKeys - * @return {Array} The string based keys in the Cache. - */ - getSoundKeys: function () { - return this.getKeys(this._sounds); - }, - - /** - * Returns an array containing all of the keys of Text Files in the Cache. - * - * @method Phaser.Cache#getTextKeys - * @return {Array} The string based keys in the Cache. - */ - getTextKeys: function () { - return this.getKeys(this._text); - }, - - /** - * Removes a canvas from the cache. - * - * @method Phaser.Cache#removeCanvas - * @param {string} key - Key of the asset you want to remove. - */ - removeCanvas: function (key) { - delete this._canvases[key]; - }, - - /** - * Removes an image from the cache. - * - * @method Phaser.Cache#removeImage - * @param {string} key - Key of the asset you want to remove. - */ - removeImage: function (key) { - delete this._images[key]; - }, - - /** - * Removes a sound from the cache. - * - * @method Phaser.Cache#removeSound - * @param {string} key - Key of the asset you want to remove. - */ - removeSound: function (key) { - delete this._sounds[key]; - }, - - /** - * Removes a text from the cache. - * - * @method Phaser.Cache#removeText - * @param {string} key - Key of the asset you want to remove. - */ - removeText: function (key) { - delete this._text[key]; - }, - - /** - * Clears the cache. Removes every local cache object reference. - * - * @method Phaser.Cache#destroy - */ - destroy: function () { - - for (var item in this._canvases) - { - delete this._canvases[item['key']]; - } - - for (var item in this._images) - { - delete this._images[item['key']]; - } - - for (var item in this._sounds) - { - delete this._sounds[item['key']]; - } - - for (var item in this._text) - { - delete this._text[item['key']]; - } - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser loader constructor. -* The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. -* It uses a combination of Image() loading and xhr and provides progress and completion callbacks. -* @class Phaser.Loader -* @classdesc The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files. -* It uses a combination of Image() loading and xhr and provides progress and completion callbacks. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Loader = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {array} _keys - Array stores assets keys. So you can get that asset by its unique key. - * @private - */ - this._keys = []; - - /** - * @property {Description} _fileList - Contains all the assets file infos. - * @private - */ - this._fileList = {}; - - /** - * @property {number} _progressChunk - Indicates assets loading progress. (from 0 to 100) - * @private - * @default - */ - this._progressChunk = 0; - - /** - * @property {XMLHttpRequest} - An XMLHttpRequest object used for loading text and audio data. - * @private - */ - this._xhr = new XMLHttpRequest(); - - /** - * @property {number} - Length of assets queue. - * @default - */ - this.queueSize = 0; - - /** - * @property {boolean} isLoading - True if the Loader is in the process of loading the queue. - * @default - */ - this.isLoading = false; - - /** - * @property {boolean} hasLoaded - True if all assets in the queue have finished loading. - * @default - */ - this.hasLoaded = false; - - /** - * @property {number} progress - The Load progress percentage value (from 0 to 100) - * @default - */ - this.progress = 0; - - /** - * You can optionally link a sprite to the preloader. - * If you do so the Sprite's width or height will be cropped based on the percentage loaded. - * @property {Description} preloadSprite - * @default - */ - this.preloadSprite = null; - - /** - * @property {string} crossOrigin - The crossOrigin value applied to loaded images - */ - this.crossOrigin = ''; - - /** - * If you want to append a URL before the path of any asset you can set this here. - * Useful if you need to allow an asset url to be configured outside of the game code. - * MUST have / on the end of it! - * @property {string} baseURL - * @default - */ - this.baseURL = ''; - - /** - * @property {Phaser.Signal} onFileComplete - Event signal. - */ - this.onFileComplete = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onFileError - Event signal. - */ - this.onFileError = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onLoadStart - Event signal. - */ - this.onLoadStart = new Phaser.Signal; - - /** - * @property {Phaser.Signal} onLoadComplete - Event signal. - */ - this.onLoadComplete = new Phaser.Signal; - -}; - -/** -* @constant -* @type {number} -*/ -Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0; - -/** -* @constant -* @type {number} -*/ -Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1; - -/** -* @constant -* @type {number} -*/ -Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2; - -Phaser.Loader.prototype = { - - /** - * You can set a Sprite to be a "preload" sprite by passing it to this method. - * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time. - * This allows you to easily make loading bars for games. - * - * @method Phaser.Loader#setPreloadSprite - * @param {Phaser.Sprite} sprite - The sprite that will be cropped during the load. - * @param {number} [direction=0] - A value of zero means the sprite width will be cropped, a value of 1 means its height will be cropped. - */ - setPreloadSprite: function (sprite, direction) { - - direction = direction || 0; - - this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, crop: null }; - - if (direction == 0) - { - // Horizontal crop - this.preloadSprite.crop = new Phaser.Rectangle(0, 0, 1, sprite.height); - } - else - { - // Vertical crop - this.preloadSprite.crop = new Phaser.Rectangle(0, 0, sprite.width, 1); - } - - sprite.crop = this.preloadSprite.crop; - sprite.cropEnabled = true; - - }, - - /** - * Check whether asset exists with a specific key. - * - * @method Phaser.Loader#checkKeyExists - * @param {string} key - Key of the asset you want to check. - * @return {boolean} Return true if exists, otherwise return false. - */ - checkKeyExists: function (key) { - - if (this._fileList[key]) - { - return true; - } - else - { - return false; - } - - }, - - /** - * Reset loader, this will remove all loaded assets. - * - * @method Phaser.Loader#reset - */ - reset: function () { - - this.preloadSprite = null; - this.queueSize = 0; - this.isLoading = false; - - }, - - /** - * Internal function that adds a new entry to the file list. Do not call directly. - * - * @method Phaser.Loader#addToFileList - * @param {Description} type - Description. - * @param {string} key - Description. - * @param {string} url - URL of Description. - * @param {Description} properties - Description. - * @protected - */ - addToFileList: function (type, key, url, properties) { - - var entry = { - type: type, - key: key, - url: url, - data: null, - error: false, - loaded: false - }; - - if (typeof properties !== "undefined") - { - for (var prop in properties) - { - entry[prop] = properties[prop]; - } - } - - this._fileList[key] = entry; - - this._keys.push(key); - - this.queueSize++; - - }, - - /** - * Add an image to the Loader. - * - * @method Phaser.Loader#image - * @param {string} key - Unique asset key of this image file. - * @param {string} url - URL of image file. - * @param {boolean} overwrite - If an entry with a matching key already exists this will over-write it - */ - image: function (key, url, overwrite) { - - if (typeof overwrite === "undefined") { overwrite = false; } - - if (overwrite || this.checkKeyExists(key) == false) - { - this.addToFileList('image', key, url); - } - - return this; - - }, - - /** - * Add a text file to the Loader. - * - * @method Phaser.Loader#text - * @param {string} key - Unique asset key of the text file. - * @param {string} url - URL of the text file. - * @param {boolean} overwrite - True if Description. - */ - text: function (key, url, overwrite) { - - if (typeof overwrite === "undefined") { overwrite = false; } - - if (overwrite || this.checkKeyExists(key) == false) - { - this.addToFileList('text', key, url); - } - - return this; - - }, - - /** - * Add a new sprite sheet to the loader. - * - * @method Phaser.Loader#spritesheet - * @param {string} key - Unique asset key of the sheet file. - * @param {string} url - URL of the sheet file. - * @param {number} frameWidth - Width of each single frame. - * @param {number} frameHeight - Height of each single frame. - * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames. - */ - spritesheet: function (key, url, frameWidth, frameHeight, frameMax) { - - if (typeof frameMax === "undefined") { frameMax = -1; } - - if (this.checkKeyExists(key) === false) - { - this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax }); - } - - return this; - - }, - - /** - * Add a new tile set to the loader. These are used in the rendering of tile maps. - * - * @method Phaser.Loader#tileset - * @param {string} key - Unique asset key of the tileset file. - * @param {string} url - URL of the tileset. - * @param {number} tileWidth - Width of each single tile in pixels. - * @param {number} tileHeight - Height of each single tile in pixels. - * @param {number} [tileMax=-1] - How many tiles in this tileset. If not specified it will divide the whole image into tiles. - * @param {number} [tileMargin=0] - If the tiles have been drawn with a margin, specify the amount here. - * @param {number} [tileSpacing=0] - If the tiles have been drawn with spacing between them, specify the amount here. - */ - tileset: function (key, url, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { - - if (typeof tileMax === "undefined") { tileMax = -1; } - if (typeof tileMargin === "undefined") { tileMargin = 0; } - if (typeof tileSpacing === "undefined") { tileSpacing = 0; } - - if (this.checkKeyExists(key) === false) - { - this.addToFileList('tileset', key, url, { tileWidth: tileWidth, tileHeight: tileHeight, tileMax: tileMax, tileMargin: tileMargin, tileSpacing: tileSpacing }); - } - - return this; - - }, - - /** - * Add a new audio file to the loader. - * - * @method Phaser.Loader#audio - * @param {string} key - Unique asset key of the audio file. - * @param {Array} urls - An array containing the URLs of the audio files, i.e.: [ 'jump.mp3', 'jump.ogg', 'jump.m4a' ]. - * @param {boolean} autoDecode - When using Web Audio the audio files can either be decoded at load time or run-time. They can't be played until they are decoded, but this let's you control when that happens. Decoding is a non-blocking async process. - */ - audio: function (key, urls, autoDecode) { - - if (typeof autoDecode === "undefined") { autoDecode = true; } - - if (this.checkKeyExists(key) === false) - { - this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode }); - } - - return this; - - }, - - /** - * Add a new tilemap loading request. - * - * @method Phaser.Loader#tilemap - * @param {string} key - Unique asset key of the tilemap data. - * @param {string} tilesetURL - The url of the tile set image file. - * @param {string} [mapDataURL] - The url of the map data file (csv/json) - * @param {object} [mapData] - An optional JSON data object (can be given in place of a URL). - * @param {string} [format] - The format of the map data. - */ - tilemap: function (key, mapDataURL, mapData, format) { - - if (typeof mapDataURL === "undefined") { mapDataURL = null; } - if (typeof mapData === "undefined") { mapData = null; } - if (typeof format === "undefined") { format = Phaser.Tilemap.CSV; } - - if (mapDataURL == null && mapData == null) - { - console.warn('Phaser.Loader.tilemap - Both mapDataURL and mapData are null. One must be set.'); - - return this; - } - - if (this.checkKeyExists(key) === false) - { - // A URL to a json/csv file has been given - if (mapDataURL) - { - this.addToFileList('tilemap', key, mapDataURL, { format: format }); - } - else - { - switch (format) - { - // A csv string or object has been given - case Phaser.Tilemap.CSV: - break; - - // An xml string or object has been given - case Phaser.Tilemap.TILED_JSON: - - if (typeof mapData === 'string') - { - mapData = JSON.parse(mapData); - } - break; - } - - this.game.cache.addTilemap(key, null, mapData, format); - - } - } - - return this; - - }, - - /** - * Add a new bitmap font loading request. - * - * @method Phaser.Loader#bitmapFont - * @param {string} key - Unique asset key of the bitmap font. - * @param {string} textureURL - The url of the font image file. - * @param {string} [xmlURL] - The url of the font data file (xml/fnt) - * @param {object} [xmlData] - An optional XML data object. - */ - bitmapFont: function (key, textureURL, xmlURL, xmlData) { - - if (typeof xmlURL === "undefined") { xmlURL = null; } - if (typeof xmlData === "undefined") { xmlData = null; } - - if (this.checkKeyExists(key) === false) - { - // A URL to a json/xml file has been given - if (xmlURL) - { - this.addToFileList('bitmapfont', key, textureURL, { xmlURL: xmlURL }); - } - else - { - // An xml string or object has been given - if (typeof xmlData === 'string') - { - var xml; - - try { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(xmlData, "text/xml"); - } - else - { - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = 'false'; - xml.loadXML(xmlData); - } - } - catch (e) - { - xml = undefined; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) - { - throw new Error("Phaser.Loader. Invalid Bitmap Font XML given"); - } - else - { - this.addToFileList('bitmapfont', key, textureURL, { xmlURL: null, xmlData: xml }); - } - } - } - } - - return this; - - }, - - /** - * Add a new texture atlas to the loader. This atlas uses the JSON Array data format. - * - * @method Phaser.Loader#atlasJSONArray - * @param {string} key - Unique asset key of the bitmap font. - * @param {Description} atlasURL - The url of the Description. - * @param {Description} atlasData - Description. - */ - atlasJSONArray: function (key, textureURL, atlasURL, atlasData) { - - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY); - - }, - - /** - * Add a new texture atlas to the loader. This atlas uses the JSON Hash data format. - * - * @method Phaser.Loader#atlasJSONHash - * @param {string} key - Unique asset key of the bitmap font. - * @param {Description} atlasURL - The url of the Description. - * @param {Description} atlasData - Description. - */ - atlasJSONHash: function (key, textureURL, atlasURL, atlasData) { - - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH); - - }, - - /** - * Add a new texture atlas to the loader. This atlas uses the Starling XML data format. - * - * @method Phaser.Loader#atlasXML - * @param {string} key - Unique asset key of the bitmap font. - * @param {Description} atlasURL - The url of the Description. - * @param {Description} atlasData - Description. - */ - atlasXML: function (key, textureURL, atlasURL, atlasData) { - - return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING); - - }, - - /** - * Add a new texture atlas to the loader. - * - * @method Phaser.Loader#atlas - * @param {string} key - Unique asset key of the texture atlas file. - * @param {string} textureURL - The url of the texture atlas image file. - * @param {string} [atlasURL] - The url of the texture atlas data file (json/xml). You don't need this if you are passing an atlasData object instead. - * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL. - * @param {number} [format] - A value describing the format of the data, the default is Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY. - */ - atlas: function (key, textureURL, atlasURL, atlasData, format) { - - if (typeof atlasURL === "undefined") { atlasURL = null; } - if (typeof atlasData === "undefined") { atlasData = null; } - if (typeof format === "undefined") { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; } - - if (this.checkKeyExists(key) === false) - { - // A URL to a json/xml file has been given - if (atlasURL) - { - this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format }); - } - else - { - switch (format) - { - // A json string or object has been given - case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY: - - if (typeof atlasData === 'string') - { - atlasData = JSON.parse(atlasData); - } - break; - - // An xml string or object has been given - case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING: - - if (typeof atlasData === 'string') - { - var xml; - - try { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(atlasData, "text/xml"); - } - else - { - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = 'false'; - xml.loadXML(atlasData); - } - } - catch (e) - { - xml = undefined; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) - { - throw new Error("Phaser.Loader. Invalid Texture Atlas XML given"); - } - else - { - atlasData = xml; - } - } - break; - } - - this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format }); - - } - - } - - return this; - - }, - - /** - * Remove loading request of a file. - * - * @method Phaser.Loader#removeFile - * @param key {string} Key of the file you want to remove. - */ - removeFile: function (key) { - - delete this._fileList[key]; - - }, - - /** - * Remove all file loading requests. - * - * @method Phaser.Loader#removeAll - */ - removeAll: function () { - - this._fileList = {}; - - }, - - /** - * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so. - * - * @method Phaser.Loader#start - */ - start: function () { - - if (this.isLoading) - { - return; - } - - this.progress = 0; - this.hasLoaded = false; - this.isLoading = true; - - this.onLoadStart.dispatch(this.queueSize); - - if (this._keys.length > 0) - { - this._progressChunk = 100 / this._keys.length; - this.loadFile(); - } - else - { - this.progress = 100; - this.hasLoaded = true; - this.onLoadComplete.dispatch(); - } - - }, - - /** - * Load files. Private method ONLY used by loader. - * - * @method Phaser.Loader#loadFile - * @private - */ - loadFile: function () { - - var file = this._fileList[this._keys.shift()]; - var _this = this; - - // Image or Data? - switch (file.type) - { - case 'image': - case 'spritesheet': - case 'textureatlas': - case 'bitmapfont': - case 'tileset': - file.data = new Image(); - file.data.name = file.key; - file.data.onload = function () { - return _this.fileComplete(file.key); - }; - file.data.onerror = function () { - return _this.fileError(file.key); - }; - file.data.crossOrigin = this.crossOrigin; - file.data.src = this.baseURL + file.url; - break; - - case 'audio': - file.url = this.getAudioURL(file.url); - - if (file.url !== null) - { - // WebAudio or Audio Tag? - if (this.game.sound.usingWebAudio) - { - this._xhr.open("GET", this.baseURL + file.url, true); - this._xhr.responseType = "arraybuffer"; - this._xhr.onload = function () { - return _this.fileComplete(file.key); - }; - this._xhr.onerror = function () { - return _this.fileError(file.key); - }; - this._xhr.send(); - } - else if (this.game.sound.usingAudioTag) - { - if (this.game.sound.touchLocked) - { - // If audio is locked we can't do this yet, so need to queue this load request. Bum. - file.data = new Audio(); - file.data.name = file.key; - file.data.preload = 'auto'; - file.data.src = this.baseURL + file.url; - this.fileComplete(file.key); - } - else - { - file.data = new Audio(); - file.data.name = file.key; - file.data.onerror = function () { - return _this.fileError(file.key); - }; - file.data.preload = 'auto'; - file.data.src = this.baseURL + file.url; - file.data.addEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete(file.key), false); - file.data.load(); - } - } - } - else - { - this.fileError(file.key); - } - - break; - - case 'tilemap': - this._xhr.open("GET", this.baseURL + file.url, true); - this._xhr.responseType = "text"; - - if (file.format == Phaser.Tilemap.TILED_JSON) - { - this._xhr.onload = function () { - return _this.jsonLoadComplete(file.key); - }; - } - else if (file.format == Phaser.Tilemap.CSV) - { - this._xhr.onload = function () { - return _this.csvLoadComplete(file.key); - }; - } - else - { - throw new Error("Phaser.Loader. Invalid Tilemap format: " + file.format); - } - - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - break; - - case 'text': - this._xhr.open("GET", this.baseURL + file.url, true); - this._xhr.responseType = "text"; - this._xhr.onload = function () { - return _this.fileComplete(file.key); - }; - this._xhr.onerror = function () { - return _this.fileError(file.key); - }; - this._xhr.send(); - break; - } - - }, - - /** - * Private method ONLY used by loader. - * @method Phaser.Loader#getAudioURL - * @param {Description} urls - Description. - * @private - */ - getAudioURL: function (urls) { - - var extension; - - for (var i = 0; i < urls.length; i++) - { - extension = urls[i].toLowerCase(); - extension = extension.substr((Math.max(0, extension.lastIndexOf(".")) || Infinity) + 1); - - if (this.game.device.canPlayAudio(extension)) - { - return urls[i]; - } - - } - - return null; - - }, - - /** - * Error occured when load a file. - * - * @method Phaser.Loader#fileError - * @param {string} key - Key of the error loading file. - */ - fileError: function (key) { - - this._fileList[key].loaded = true; - this._fileList[key].error = true; - - this.onFileError.dispatch(key); - - console.warn("Phaser.Loader error loading file: " + key + ' from URL ' + this._fileList[key].url); - - this.nextFile(key, false); - - }, - - /** - * Called when a file is successfully loaded. - * - * @method Phaser.Loader#fileComplete - * @param {string} key - Key of the successfully loaded file. - */ - fileComplete: function (key) { - - if (!this._fileList[key]) - { - console.warn('Phaser.Loader fileComplete invalid key ' + key); - return; - } - - this._fileList[key].loaded = true; - - var file = this._fileList[key]; - var loadNext = true; - var _this = this; - - switch (file.type) - { - case 'image': - - this.game.cache.addImage(file.key, file.url, file.data); - break; - - case 'spritesheet': - - this.game.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax); - break; - - case 'tileset': - - this.game.cache.addTileset(file.key, file.url, file.data, file.tileWidth, file.tileHeight, file.tileMax, file.tileMargin, file.tileSpacing); - break; - - case 'textureatlas': - - if (file.atlasURL == null) - { - this.game.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format); - } - else - { - // Load the JSON or XML before carrying on with the next file - loadNext = false; - this._xhr.open("GET", this.baseURL + file.atlasURL, true); - this._xhr.responseType = "text"; - - if (file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format == Phaser.Loader.TEXTURE_ATLAS_JSON_HASH) - { - this._xhr.onload = function () { - return _this.jsonLoadComplete(file.key); - }; - } - else if (file.format == Phaser.Loader.TEXTURE_ATLAS_XML_STARLING) - { - this._xhr.onload = function () { - return _this.xmlLoadComplete(file.key); - }; - } - else - { - throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format); - } - - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - } - break; - - case 'bitmapfont': - - if (file.xmlURL == null) - { - this.game.cache.addBitmapFont(file.key, file.url, file.data, file.xmlData); - } - else - { - // Load the XML before carrying on with the next file - loadNext = false; - this._xhr.open("GET", this.baseURL + file.xmlURL, true); - this._xhr.responseType = "text"; - - this._xhr.onload = function () { - return _this.xmlLoadComplete(file.key); - }; - - this._xhr.onerror = function () { - return _this.dataLoadError(file.key); - }; - this._xhr.send(); - } - break; - - case 'audio': - - if (this.game.sound.usingWebAudio) - { - file.data = this._xhr.response; - - this.game.cache.addSound(file.key, file.url, file.data, true, false); - - if (file.autoDecode) - { - this.game.cache.updateSound(key, 'isDecoding', true); - - var that = this; - var key = file.key; - - this.game.sound.context.decodeAudioData(file.data, function (buffer) { - if (buffer) - { - that.game.cache.decodedSound(key, buffer); - } - }); - } - } - else - { - file.data.removeEventListener('canplaythrough', Phaser.GAMES[this.game.id].load.fileComplete); - this.game.cache.addSound(file.key, file.url, file.data, false, true); - } - break; - - case 'text': - file.data = this._xhr.responseText; - this.game.cache.addText(file.key, file.url, file.data); - break; - } - - if (loadNext) - { - this.nextFile(key, true); - } - - }, - - /** - * Successfully loaded a JSON file. - * - * @method Phaser.Loader#jsonLoadComplete - * @param {string} key - Key of the loaded JSON file. - */ - jsonLoadComplete: function (key) { - - var data = JSON.parse(this._xhr.responseText); - var file = this._fileList[key]; - - if (file.type == 'tilemap') - { - this.game.cache.addTilemap(file.key, file.url, data, file.format); - } - else - { - this.game.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format); - } - - this.nextFile(key, true); - - }, - - /** - * Successfully loaded a CSV file. - * - * @method Phaser.Loader#csvLoadComplete - * @param {string} key - Key of the loaded CSV file. - */ - csvLoadComplete: function (key) { - - var data = this._xhr.responseText; - var file = this._fileList[key]; - - this.game.cache.addTilemap(file.key, file.url, data, file.format); - - this.nextFile(key, true); - - }, - - /** - * Error occured when load a JSON. - * - * @method Phaser.Loader#dataLoadError - * @param {string} key - Key of the error loading JSON file. - */ - dataLoadError: function (key) { - - var file = this._fileList[key]; - - file.error = true; - - console.warn("Phaser.Loader dataLoadError: " + key); - - this.nextFile(key, true); - - }, - - /** - * Successfully loaded an XML file. - * - * @method Phaser.Loader#xmlLoadComplete - * @param {string} key - Key of the loaded XML file. - */ - xmlLoadComplete: function (key) { - - var data = this._xhr.responseText; - var xml; - - try - { - if (window['DOMParser']) - { - var domparser = new DOMParser(); - xml = domparser.parseFromString(data, "text/xml"); - } - else - { - xml = new ActiveXObject("Microsoft.XMLDOM"); - xml.async = 'false'; - xml.loadXML(data); - } - } - catch (e) - { - xml = undefined; - } - - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) - { - throw new Error("Phaser.Loader. Invalid XML given"); - } - - var file = this._fileList[key]; - - if (file.type == 'bitmapfont') - { - this.game.cache.addBitmapFont(file.key, file.url, file.data, xml); - } - else if (file.type == 'textureatlas') - { - this.game.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format); - } - - this.nextFile(key, true); - - }, - - /** - * Handle loading next file. - * - * @param previousKey {string} Key of previous loaded asset. - * @param success {boolean} Whether the previous asset loaded successfully or not. - * @private - */ - nextFile: function (previousKey, success) { - - this.progress = Math.round(this.progress + this._progressChunk); - - if (this.progress > 100) - { - this.progress = 100; - } - - if (this.preloadSprite !== null) - { - if (this.preloadSprite.direction == 0) - { - this.preloadSprite.crop.width = Math.floor((this.preloadSprite.width / 100) * this.progress); - } - else - { - this.preloadSprite.crop.height = Math.floor((this.preloadSprite.height / 100) * this.progress); - } - - this.preloadSprite.sprite.crop = this.preloadSprite.crop; - } - - this.onFileComplete.dispatch(this.progress, previousKey, success, this.queueSize - this._keys.length, this.queueSize); - - if (this._keys.length > 0) - { - this.loadFile(); - } - else - { - this.hasLoaded = true; - this.isLoading = false; - - this.removeAll(); - - this.onLoadComplete.dispatch(); - } - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache. -* -* @class Phaser.LoaderParser -*/ -Phaser.LoaderParser = { - - /** - * Parse frame data from an XML file. - * @method Phaser.LoaderParser.bitmapFont - * @param {object} xml - XML data you want to parse. - * @return {FrameData} Generated FrameData object. - */ - bitmapFont: function (game, xml, cacheKey) { - - // Malformed? - if (!xml.getElementsByTagName('font')) - { - console.warn("Phaser.LoaderParser.bitmapFont: Invalid XML given, missing tag"); - return; - } - - var texture = PIXI.TextureCache[cacheKey]; - - var data = {}; - var info = xml.getElementsByTagName("info")[0]; - var common = xml.getElementsByTagName("common")[0]; - data.font = info.attributes.getNamedItem("face").nodeValue; - data.size = parseInt(info.attributes.getNamedItem("size").nodeValue, 10); - data.lineHeight = parseInt(common.attributes.getNamedItem("lineHeight").nodeValue, 10); - data.chars = {}; - - //parse letters - var letters = xml.getElementsByTagName("char"); - - for (var i = 0; i < letters.length; i++) - { - var charCode = parseInt(letters[i].attributes.getNamedItem("id").nodeValue, 10); - - var textureRect = { - x: parseInt(letters[i].attributes.getNamedItem("x").nodeValue, 10), - y: parseInt(letters[i].attributes.getNamedItem("y").nodeValue, 10), - width: parseInt(letters[i].attributes.getNamedItem("width").nodeValue, 10), - height: parseInt(letters[i].attributes.getNamedItem("height").nodeValue, 10) - }; - - // Note: This means you can only have 1 BitmapFont loaded at once! - // Need to replace this with our own handler soon. - PIXI.TextureCache[charCode] = new PIXI.Texture(texture, textureRect); - - data.chars[charCode] = { - xOffset: parseInt(letters[i].attributes.getNamedItem("xoffset").nodeValue, 10), - yOffset: parseInt(letters[i].attributes.getNamedItem("yoffset").nodeValue, 10), - xAdvance: parseInt(letters[i].attributes.getNamedItem("xadvance").nodeValue, 10), - kerning: {}, - texture:new PIXI.Texture(texture, textureRect) - - }; - } - - //parse kernings - var kernings = xml.getElementsByTagName("kerning"); - - for (i = 0; i < kernings.length; i++) - { - var first = parseInt(kernings[i].attributes.getNamedItem("first").nodeValue, 10); - var second = parseInt(kernings[i].attributes.getNamedItem("second").nodeValue, 10); - var amount = parseInt(kernings[i].attributes.getNamedItem("amount").nodeValue, 10); - - data.chars[second].kerning[first] = amount; - } - - PIXI.BitmapText.fonts[data.font] = data; - - } - -}; -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Sound class constructor. -* -* @class Phaser.Sound -* @classdesc The Sound class -* @constructor -* @param {Phaser.Game} game - Reference to the current game instance. -* @param {string} key - Asset key for the sound. -* @param {number} [volume=1] - Default value for the volume, between 0 and 1. -* @param {boolean} [loop=false] - Whether or not the sound will loop. -*/ -Phaser.Sound = function (game, key, volume, loop) { - - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } - - /** - * A reference to the currently running Game. - * @property {Phaser.Game} game - */ - this.game = game; - - /** - * Name of the sound. - * @property {string} name - * @default - */ - this.name = key; - - /** - * Asset key for the sound. - * @property {string} key - */ - this.key = key; - - /** - * Whether or not the sound will loop. - * @property {boolean} loop - */ - this.loop = loop; - - /** - * The global audio volume. A value between 0 (silence) and 1 (full volume). - * @property {number} _volume - * @private - */ - this._volume = volume; - - /** - * The sound markers, empty by default. - * @property {object} markers - */ - this.markers = {}; - - - /** - * Reference to AudioContext instance. - * @property {AudioContext} context - * @default - */ - this.context = null; - - /** - * Decoded data buffer / Audio tag. - * @property {Description} _buffer - * @private - */ - this._buffer = null; - - /** - * Boolean indicating whether the game is on "mute". - * @property {boolean} _muted - * @private - * @default - */ - this._muted = false; - - /** - * Boolean indicating whether the sound should start automatically. - * @property {boolean} autoplay - * @private - */ - this.autoplay = false; - - /** - * The total duration of the sound, in milliseconds - * @property {number} totalDuration - * @default - */ - this.totalDuration = 0; - - /** - * Description. - * @property {number} startTime - * @default - */ - this.startTime = 0; - - /** - * Description. - * @property {number} currentTime - * @default - */ - this.currentTime = 0; - - /** - * Description. - * @property {number} duration - * @default - */ - this.duration = 0; - - /** - * Description. - * @property {number} stopTime - */ - this.stopTime = 0; - - /** - * Description. - * @property {boolean} paused - * @default - */ - this.paused = false; - - /** - * Description. - * @property {number} pausedPosition - */ - this.pausedPosition = 0; - - /** - * Description. - * @property {number} pausedTime - */ - this.pausedTime = 0; - - /** - * Description. - * @property {boolean} isPlaying - * @default - */ - this.isPlaying = false; - - /** - * Description. - * @property {string} currentMarker - * @default - */ - this.currentMarker = ''; - - /** - * Description. - * @property {boolean} pendingPlayback - * @default - */ - this.pendingPlayback = false; - - /** - * Description. - * @property {boolean} override - * @default - */ - this.override = false; - - /** - * Description. - * @property {boolean} usingWebAudio - */ - this.usingWebAudio = this.game.sound.usingWebAudio; - - /** - * Description. - * @property {Description} usingAudioTag - */ - this.usingAudioTag = this.game.sound.usingAudioTag; - - if (this.usingWebAudio) - { - this.context = this.game.sound.context; - this.masterGainNode = this.game.sound.masterGain; - - if (typeof this.context.createGain === 'undefined') - { - this.gainNode = this.context.createGainNode(); - } - else - { - this.gainNode = this.context.createGain(); - } - - this.gainNode.gain.value = volume * this.game.sound.volume; - this.gainNode.connect(this.masterGainNode); - } - else - { - if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key)) - { - this._sound = this.game.cache.getSoundData(key); - this.totalDuration = 0; - - if (this._sound.duration) - { - this.totalDuration = this._sound.duration; - } - } - else - { - this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this); - } - } - - /** - * Description. - * @property {Phaser.Signal} onDecoded - */ - this.onDecoded = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onPlay - */ - this.onPlay = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onPause - */ - this.onPause = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onResume - */ - this.onResume = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onLoop - */ - this.onLoop = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onStop - */ - this.onStop = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onMute - */ - this.onMute = new Phaser.Signal; - - /** - * Description. - * @property {Phaser.Signal} onMarkerComplete - */ - this.onMarkerComplete = new Phaser.Signal; - -}; - -Phaser.Sound.prototype = { - - /** - * Called automatically when this sound is unlocked. - * @method Phaser.Sound#soundHasUnlocked - * @param {string} key - Description. - * @protected - */ - soundHasUnlocked: function (key) { - - if (key == this.key) - { - this._sound = this.game.cache.getSoundData(this.key); - this.totalDuration = this._sound.duration; - // console.log('sound has unlocked' + this._sound); - } - - }, - - /** - * Description. - * @method Phaser.Sound#addMarker - * @param {string} name - Description. - * @param {Description} start - Description. - * @param {Description} stop - Description. - * @param {Description} volume - Description. - * @param {Description} loop - Description. - addMarker: function (name, start, stop, volume, loop) { - - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } - - this.markers[name] = { - name: name, - start: start, - stop: stop, - volume: volume, - duration: stop - start, - loop: loop - }; - - }, - */ - - /** - * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration. - * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback. - * - * @method Phaser.Sound#addMarker - * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc. - * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. - * @param {number} duration - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc. - * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume). - * @param {boolean} [loop=false] - Sets if the sound will loop or not. - */ - addMarker: function (name, start, duration, volume, loop) { - - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } - - this.markers[name] = { - name: name, - start: start, - stop: start + duration, - volume: volume, - duration: duration, - durationMS: duration * 1000, - loop: loop - }; - - }, - - /** - * Removes a marker from the sound. - * @method Phaser.Sound#removeMarker - * @param {string} name - The key of the marker to remove. - */ - removeMarker: function (name) { - - delete this.markers[name]; - - }, - - /** - * Called automatically by Phaser.SoundManager. - * @method Phaser.Sound#update - * @protected - */ - update: function () { - - if (this.pendingPlayback && this.game.cache.isSoundReady(this.key)) - { - this.pendingPlayback = false; - this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop); - } - - if (this.isPlaying) - { - this.currentTime = this.game.time.now - this.startTime; - - if (this.currentTime >= this.durationMS) - { - //console.log(this.currentMarker, 'has hit duration'); - if (this.usingWebAudio) - { - if (this.loop) - { - //console.log('loop1'); - // won't work with markers, needs to reset the position - this.onLoop.dispatch(this); - - if (this.currentMarker == '') - { - //console.log('loop2'); - this.currentTime = 0; - this.startTime = this.game.time.now; - } - else - { - //console.log('loop3'); - this.play(this.currentMarker, 0, this.volume, true, true); - } - } - else - { - //console.log('stopping, no loop for marker'); - this.stop(); - } - } - else - { - if (this.loop) - { - this.onLoop.dispatch(this); - this.play(this.currentMarker, 0, this.volume, true, true); - } - else - { - this.stop(); - } - } - } - } - }, - - /** - * Play this sound, or a marked section of it. - * @method Phaser.Sound#play - * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. - * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. - * @param {number} [volume=1] - Volume of the sound you want to play. - * @param {boolean} [loop=false] - Loop when it finished playing? - * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning. - * @return {Sound} The playing sound object. - */ - play: function (marker, position, volume, loop, forceRestart) { - - marker = marker || ''; - position = position || 0; - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } - if (typeof forceRestart == 'undefined') { forceRestart = true; } - - // console.log(this.name + ' play ' + marker + ' position ' + position + ' volume ' + volume + ' loop ' + loop, 'force', forceRestart); - - if (this.isPlaying == true && forceRestart == false && this.override == false) - { - // Use Restart instead - return; - } - - if (this.isPlaying && this.override) - { - // console.log('asked to play ' + marker + ' but already playing ' + this.currentMarker); - - if (this.usingWebAudio) - { - if (typeof this._sound.stop === 'undefined') - { - this._sound.noteOff(0); - } - else - { - this._sound.stop(0); - } - } - else if (this.usingAudioTag) - { - this._sound.pause(); - this._sound.currentTime = 0; - } - } - - this.currentMarker = marker; - - if (marker !== '') - { - if (this.markers[marker]) - { - this.position = this.markers[marker].start; - this.volume = this.markers[marker].volume; - this.loop = this.markers[marker].loop; - this.duration = this.markers[marker].duration; - this.durationMS = this.markers[marker].durationMS; - - // console.log('Marker Loaded: ', marker, 'start:', this.position, 'end: ', this.duration, 'loop', this.loop); - - this._tempMarker = marker; - this._tempPosition = this.position; - this._tempVolume = this.volume; - this._tempLoop = this.loop; - } - else - { - console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist"); - return; - } - } - else - { - // console.log('no marker info loaded', marker); - - this.position = position; - this.volume = volume; - this.loop = loop; - this.duration = 0; - this.durationMS = 0; - - this._tempMarker = marker; - this._tempPosition = position; - this._tempVolume = volume; - this._tempLoop = loop; - } - - if (this.usingWebAudio) - { - // Does the sound need decoding? - if (this.game.cache.isSoundDecoded(this.key)) - { - // Do we need to do this every time we play? How about just if the buffer is empty? - if (this._buffer == null) - { - this._buffer = this.game.cache.getSoundData(this.key); - } - - this._sound = this.context.createBufferSource(); - this._sound.buffer = this._buffer; - this._sound.connect(this.gainNode); - this.totalDuration = this._sound.buffer.duration; - - if (this.duration == 0) - { - // console.log('duration reset'); - this.duration = this.totalDuration; - this.durationMS = this.totalDuration * 1000; - } - - if (this.loop && marker == '') - { - this._sound.loop = true; - } - - // Useful to cache this somewhere perhaps? - if (typeof this._sound.start === 'undefined') - { - this._sound.noteGrainOn(0, this.position, this.duration); - // this._sound.noteGrainOn(0, this.position, this.duration / 1000); - //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it - } - else - { - // this._sound.start(0, this.position, this.duration / 1000); - this._sound.start(0, this.position, this.duration); - } - - this.isPlaying = true; - this.startTime = this.game.time.now; - this.currentTime = 0; - this.stopTime = this.startTime + this.durationMS; - this.onPlay.dispatch(this); - } - else - { - this.pendingPlayback = true; - - if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding == false) - { - this.game.sound.decode(this.key, this); - } - } - } - else - { - // console.log('Sound play Audio'); - if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked) - { - // console.log('tried playing locked sound, pending set, reload started'); - this.game.cache.reloadSound(this.key); - this.pendingPlayback = true; - } - else - { - // console.log('sound not locked, state?', this._sound.readyState); - if (this._sound && this._sound.readyState == 4) - { - this._sound.play(); - // This doesn't become available until you call play(), wonderful ... - this.totalDuration = this._sound.duration; - - if (this.duration == 0) - { - this.duration = this.totalDuration; - this.durationMS = this.totalDuration * 1000; - } - - // console.log('playing', this._sound); - this._sound.currentTime = this.position; - this._sound.muted = this._muted; - - if (this._muted) - { - this._sound.volume = 0; - } - else - { - this._sound.volume = this._volume; - } - - this.isPlaying = true; - this.startTime = this.game.time.now; - this.currentTime = 0; - this.stopTime = this.startTime + this.durationMS; - this.onPlay.dispatch(this); - } - else - { - this.pendingPlayback = true; - } - } - } - }, - - /** - * Restart the sound, or a marked section of it. - * @method Phaser.Sound#restart - * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound. - * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker. - * @param {number} [volume=1] - Volume of the sound you want to play. - * @param {boolean} [loop=false] - Loop when it finished playing? - */ - restart: function (marker, position, volume, loop) { - - marker = marker || ''; - position = position || 0; - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } - - this.play(marker, position, volume, loop, true); - - }, - - /** - * Pauses the sound - * @method Phaser.Sound#pause - */ - pause: function () { - - if (this.isPlaying && this._sound) - { - this.stop(); - this.isPlaying = false; - this.paused = true; - this.pausedPosition = this.currentTime; - this.pausedTime = this.game.time.now; - this.onPause.dispatch(this); - } - - }, - - /** - * Resumes the sound - * @method Phaser.Sound#resume - */ - resume: function () { - - if (this.paused && this._sound) - { - if (this.usingWebAudio) - { - var p = this.position + (this.pausedPosition / 1000); - - this._sound = this.context.createBufferSource(); - this._sound.buffer = this._buffer; - this._sound.connect(this.gainNode); - - if (typeof this._sound.start === 'undefined') - { - this._sound.noteGrainOn(0, p, this.duration); - //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it - } - else - { - this._sound.start(0, p, this.duration); - } - } - else - { - this._sound.play(); - } - - this.isPlaying = true; - this.paused = false; - this.startTime += (this.game.time.now - this.pausedTime); - this.onResume.dispatch(this); - } - - }, - - /** - * Stop playing this sound. - * @method Phaser.Sound#stop - */ - stop: function () { - - if (this.isPlaying && this._sound) - { - if (this.usingWebAudio) - { - if (typeof this._sound.stop === 'undefined') - { - this._sound.noteOff(0); - } - else - { - this._sound.stop(0); - } - } - else if (this.usingAudioTag) - { - this._sound.pause(); - this._sound.currentTime = 0; - } - } - - this.isPlaying = false; - var prevMarker = this.currentMarker; - - this.currentMarker = ''; - this.onStop.dispatch(this, prevMarker); - - } - -}; - -/** -* @name Phaser.Sound#isDecoding -* @property {boolean} isDecoding - Returns true if the sound file is still decoding. -* @readonly -*/ -Object.defineProperty(Phaser.Sound.prototype, "isDecoding", { - - get: function () { - return this.game.cache.getSound(this.key).isDecoding; - } - -}); - -/** -* @name Phaser.Sound#isDecoded -* @property {boolean} isDecoded - Returns true if the sound file has decoded. -* @readonly -*/ -Object.defineProperty(Phaser.Sound.prototype, "isDecoded", { - - get: function () { - return this.game.cache.isSoundDecoded(this.key); - } - -}); - -/** -* @name Phaser.Sound#mute -* @property {boolean} mute - Gets or sets the muted state of this sound. -*/ -Object.defineProperty(Phaser.Sound.prototype, "mute", { - - get: function () { - return this._muted; - }, - - set: function (value) { - - value = value || null; - - if (value) - { - this._muted = true; - - if (this.usingWebAudio) - { - this._muteVolume = this.gainNode.gain.value; - this.gainNode.gain.value = 0; - } - else if (this.usingAudioTag && this._sound) - { - this._muteVolume = this._sound.volume; - this._sound.volume = 0; - } - } - else - { - this._muted = false; - - if (this.usingWebAudio) - { - this.gainNode.gain.value = this._muteVolume; - } - else if (this.usingAudioTag && this._sound) - { - this._sound.volume = this._muteVolume; - } - } - - this.onMute.dispatch(this); - - } - -}); - -/** -* @name Phaser.Sound#volume -* @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. -* @readonly -*/ -Object.defineProperty(Phaser.Sound.prototype, "volume", { - - get: function () { - return this._volume; - }, - - set: function (value) { - - if (this.usingWebAudio) - { - this._volume = value; - this.gainNode.gain.value = value; - } - else if (this.usingAudioTag && this._sound) - { - // Causes an Index size error in Firefox if you don't clamp the value - if (value >= 0 && value <= 1) - { - this._volume = value; - this._sound.volume = value; - } - } - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Sound Manager constructor. -* The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it. -* Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files. -* -* @class Phaser.SoundManager -* @classdesc Phaser Sound Manager. -* @constructor -* @param {Phaser.Game} game reference to the current game instance. -*/ -Phaser.SoundManager = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Phaser.Signal} onSoundDecode - Description. - */ - this.onSoundDecode = new Phaser.Signal; - - /** - * @property {boolean} _muted - Description. - * @private - * @default - */ - this._muted = false; - - /** - * @property {Description} _unlockSource - Description. - * @private - * @default - */ - this._unlockSource = null; - - /** - * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume). - * @private - * @default - */ - this._volume = 1; - - /** - * @property {array} _sounds - An array containing all the sounds - * @private - * @default The empty array. - */ - this._sounds = []; - - /** - * @property {Description} context - Description. - * @default - */ - this.context = null; - - /** - * @property {boolean} usingWebAudio - Description. - * @default - */ - this.usingWebAudio = true; - - /** - * @property {boolean} usingAudioTag - Description. - * @default - */ - this.usingAudioTag = false; - - /** - * @property {boolean} noAudio - Description. - * @default - */ - this.noAudio = false; - - /** - * @property {boolean} touchLocked - Description. - * @default - */ - this.touchLocked = false; - - /** - * @property {number} channels - Description. - * @default - */ - this.channels = 32; - -}; - -Phaser.SoundManager.prototype = { - - /** - * Initialises the sound manager. - * @method Phaser.SoundManager#boot - * @protected - */ - boot: function () { - - if (this.game.device.iOS && this.game.device.webAudio == false) - { - this.channels = 1; - } - - if (this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock)) - { - this.game.input.touch.callbackContext = this; - this.game.input.touch.touchStartCallback = this.unlock; - this.game.input.mouse.callbackContext = this; - this.game.input.mouse.mouseDownCallback = this.unlock; - this.touchLocked = true; - } - else - { - // What about iOS5? - this.touchLocked = false; - } - - if (window['PhaserGlobal']) - { - // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class) - if (window['PhaserGlobal'].disableAudio == true) - { - this.usingWebAudio = false; - this.noAudio = true; - return; - } - - // Check if the Web Audio API is disabled (for testing Audio Tag playback during development) - if (window['PhaserGlobal'].disableWebAudio == true) - { - this.usingWebAudio = false; - this.usingAudioTag = true; - this.noAudio = false; - return; - } - } - - if (!!window['AudioContext']) - { - this.context = new window['AudioContext'](); - } - else if (!!window['webkitAudioContext']) - { - this.context = new window['webkitAudioContext'](); - } - else if (!!window['Audio']) - { - this.usingWebAudio = false; - this.usingAudioTag = true; - } - else - { - this.usingWebAudio = false; - this.noAudio = true; - } - - if (this.context !== null) - { - if (typeof this.context.createGain === 'undefined') - { - this.masterGain = this.context.createGainNode(); - } - else - { - this.masterGain = this.context.createGain(); - } - - this.masterGain.gain.value = 1; - this.masterGain.connect(this.context.destination); - } - - - }, - - /** - * Enables the audio, usually after the first touch. - * @method Phaser.SoundManager#unlock - */ - unlock: function () { - - if (this.touchLocked == false) - { - return; - } - - // Global override (mostly for Audio Tag testing) - if (this.game.device.webAudio == false || (window['PhaserGlobal'] && window['PhaserGlobal'].disableWebAudio == true)) - { - // Create an Audio tag? - this.touchLocked = false; - this._unlockSource = null; - this.game.input.touch.callbackContext = null; - this.game.input.touch.touchStartCallback = null; - this.game.input.mouse.callbackContext = null; - this.game.input.mouse.mouseDownCallback = null; - } - else - { - // Create empty buffer and play it - var buffer = this.context.createBuffer(1, 1, 22050); - this._unlockSource = this.context.createBufferSource(); - this._unlockSource.buffer = buffer; - this._unlockSource.connect(this.context.destination); - this._unlockSource.noteOn(0); - } - - }, - - /** - * Stops all the sounds in the game. - * @method Phaser.SoundManager#stopAll - */ - stopAll: function () { - - for (var i = 0; i < this._sounds.length; i++) - { - if (this._sounds[i]) - { - this._sounds[i].stop(); - } - } - - }, - - /** - * Pauses all the sounds in the game. - * @method Phaser.SoundManager#pauseAll - */ - pauseAll: function () { - - for (var i = 0; i < this._sounds.length; i++) - { - if (this._sounds[i]) - { - this._sounds[i].pause(); - } - } - - }, - - /** - * resumes every sound in the game. - * @method Phaser.SoundManager#resumeAll - */ - resumeAll: function () { - - for (var i = 0; i < this._sounds.length; i++) - { - if (this._sounds[i]) - { - this._sounds[i].resume(); - } - } - - }, - - /** - * Decode a sound by its assets key. - * @method Phaser.SoundManager#decode - * @param {string} key - Assets key of the sound to be decoded. - * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data. - */ - decode: function (key, sound) { - - sound = sound || null; - - var soundData = this.game.cache.getSoundData(key); - - if (soundData) - { - if (this.game.cache.isSoundDecoded(key) === false) - { - this.game.cache.updateSound(key, 'isDecoding', true); - - var that = this; - - this.context.decodeAudioData(soundData, function (buffer) { - that.game.cache.decodedSound(key, buffer); - if (sound) - { - that.onSoundDecode.dispatch(sound); - } - }); - } - } - - }, - - /** - * Updates every sound in the game. - * @method Phaser.SoundManager#update - */ - update: function () { - - if (this.touchLocked) - { - if (this.game.device.webAudio && this._unlockSource !== null) - { - if ((this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE)) - { - this.touchLocked = false; - this._unlockSource = null; - this.game.input.touch.callbackContext = null; - this.game.input.touch.touchStartCallback = null; - } - } - } - - for (var i = 0; i < this._sounds.length; i++) - { - this._sounds[i].update(); - } - - }, - - /** - * Adds a new Sound into the SoundManager. - * @method Phaser.SoundManager#add - * @param {string} key - Asset key for the sound. - * @param {number} [volume=1] - Default value for the volume. - * @param {boolean} [loop=false] - Whether or not the sound will loop. - */ - add: function (key, volume, loop) { - - volume = volume || 1; - if (typeof loop == 'undefined') { loop = false; } - - var sound = new Phaser.Sound(this.game, key, volume, loop); - - this._sounds.push(sound); - - return sound; - - } - -}; - -/** -* @name Phaser.SoundManager#mute -* @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game. -*/ -Object.defineProperty(Phaser.SoundManager.prototype, "mute", { - - get: function () { - - return this._muted; - - }, - - set: function (value) { - - value = value || null; - - if (value) - { - if (this._muted) - { - return; - } - - this._muted = true; - - if (this.usingWebAudio) - { - this._muteVolume = this.masterGain.gain.value; - this.masterGain.gain.value = 0; - } - - // Loop through sounds - for (var i = 0; i < this._sounds.length; i++) - { - if (this._sounds[i].usingAudioTag) - { - this._sounds[i].mute = true; - } - } - } - else - { - if (this._muted == false) - { - return; - } - - this._muted = false; - - if (this.usingWebAudio) - { - this.masterGain.gain.value = this._muteVolume; - } - - // Loop through sounds - for (var i = 0; i < this._sounds.length; i++) - { - if (this._sounds[i].usingAudioTag) - { - this._sounds[i].mute = false; - } - } - } - } - -}); - -/** -* @name Phaser.SoundManager#volume -* @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. -*/ -Object.defineProperty(Phaser.SoundManager.prototype, "volume", { - - get: function () { - - if (this.usingWebAudio) - { - return this.masterGain.gain.value; - } - else - { - return this._volume; - } - - }, - - set: function (value) { - - value = this.game.math.clamp(value, 1, 0); - - this._volume = value; - - if (this.usingWebAudio) - { - this.masterGain.gain.value = value; - } - - // Loop through the sound cache and change the volume of all html audio tags - for (var i = 0; i < this._sounds.length; i++) - { - if (this._sounds[i].usingAudioTag) - { - this._sounds[i].volume = this._sounds[i].volume * value; - } - } - - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A collection of methods for displaying debug information about game objects. Phaser.Debug requires a CANVAS game type in order to render, so if you've got -* your game set to use Phaser.AUTO then swap it for Phaser.CANVAS to ensure WebGL doesn't kick in, then the Debug functions will all display. -* -* @class Phaser.Utils.Debug -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Utils.Debug = function (game) { - - /** - * @property {Phaser.Game} game - A reference to the currently running Game. - */ - this.game = game; - - /** - * @property {Context} context - The canvas context on which to render the debug information. - */ - this.context = game.context; - - /** - * @property {string} font - The font that the debug information is rendered in. - * @default '14px Courier' - */ - this.font = '14px Courier'; - - /** - * @property {number} lineHeight - The line height between the debug text. - */ - this.lineHeight = 16; - - /** - * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background. - */ - this.renderShadow = true; - - /** - * @property {Context} currentX - The current X position the debug information will be rendered at. - * @default - */ - this.currentX = 0; - - /** - * @property {number} currentY - The current Y position the debug information will be rendered at. - * @default - */ - this.currentY = 0; - - /** - * @property {number} currentAlpha - The current alpha the debug information will be rendered at. - * @default - */ - this.currentAlpha = 1; - -}; - -Phaser.Utils.Debug.prototype = { - - /** - * Internal method that resets and starts the debug output values. - * @method Phaser.Utils.Debug#start - * @param {number} x - The X value the debug info will start from. - * @param {number} y - The Y value the debug info will start from. - * @param {string} color - The color the debug info will drawn in. - */ - start: function (x, y, color) { - - if (this.context == null) - { - return; - } - - if (typeof x !== 'number') { x = 0; } - if (typeof y !== 'number') { y = 0; } - - color = color || 'rgb(255,255,255)'; - - this.currentX = x; - this.currentY = y; - this.currentColor = color; - this.currentAlpha = this.context.globalAlpha; - - this.context.save(); - this.context.setTransform(1, 0, 0, 1, 0, 0); - this.context.fillStyle = color; - this.context.font = this.font; - this.context.globalAlpha = 1; - - }, - - /** - * Internal method that stops the debug output. - * @method Phaser.Utils.Debug#stop - */ - stop: function () { - - - this.context.restore(); - this.context.globalAlpha = this.currentAlpha; - - }, - - /** - * Internal method that outputs a single line of text. - * @method Phaser.Utils.Debug#line - * @param {string} text - The line of text to draw. - * @param {number} x - The X value the debug info will start from. - * @param {number} y - The Y value the debug info will start from. - */ - line: function (text, x, y) { - - if (this.context == null) - { - return; - } - - x = x || null; - y = y || null; - - if (x !== null) { - this.currentX = x; - } - - if (y !== null) { - this.currentY = y; - } - - if (this.renderShadow) - { - this.context.fillStyle = 'rgb(0,0,0)'; - this.context.fillText(text, this.currentX + 1, this.currentY + 1); - this.context.fillStyle = this.currentColor; - } - - this.context.fillText(text, this.currentX, this.currentY); - this.currentY += this.lineHeight; - - }, - - /** - * Visually renders a QuadTree to the display. - * @method Phaser.Utils.Debug#renderQuadTree - * @param {Phaser.QuadTree} quadtree - The quadtree to render. - * @param {string} color - The color of the lines in the quadtree. - */ - renderQuadTree: function (quadtree, color) { - - color = color || 'rgba(255,0,0,0.3)'; - - this.start(); - - var bounds = quadtree.bounds; - - if (quadtree.nodes.length === 0) - { - this.context.strokeStyle = color; - this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height); - this.renderText(quadtree.ID + ' / ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier'); - - this.context.strokeStyle = 'rgb(0,255,0)'; - - // children - for (var i = 0; i < quadtree.objects.length; i++) - { - this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height); - } - } - else - { - for (var i = 0; i < quadtree.nodes.length; i++) - { - this.renderQuadTree(quadtree.nodes[i]); - } - } - - this.stop(); - - }, - - /** - * Renders the corners and point information of the given Sprite. - * @method Phaser.Utils.Debug#renderSpriteCorners - * @param {Phaser.Sprite} sprite - The sprite to be rendered. - * @param {boolean} [showText=false] - If true the x/y coordinates of each point will be rendered. - * @param {boolean} [showBounds=false] - If true the bounds will be rendered over the top of the sprite. - * @param {string} [color='rgb(255,0,255)'] - The color the text is rendered in. - */ - renderSpriteCorners: function (sprite, showText, showBounds, color) { - - if (this.context == null) - { - return; - } - - showText = showText || false; - showBounds = showBounds || false; - color = color || 'rgb(255,255,255)'; - - this.start(0, 0, color); - - if (showBounds) - { - this.context.beginPath(); - this.context.strokeStyle = 'rgba(0, 255, 0, 0.7)'; - this.context.strokeRect(sprite.bounds.x, sprite.bounds.y, sprite.bounds.width, sprite.bounds.height); - this.context.closePath(); - this.context.stroke(); - } - - this.context.beginPath(); - this.context.moveTo(sprite.topLeft.x, sprite.topLeft.y); - this.context.lineTo(sprite.topRight.x, sprite.topRight.y); - this.context.lineTo(sprite.bottomRight.x, sprite.bottomRight.y); - this.context.lineTo(sprite.bottomLeft.x, sprite.bottomLeft.y); - this.context.closePath(); - this.context.strokeStyle = 'rgba(255, 0, 255, 0.7)'; - this.context.stroke(); - - this.renderPoint(sprite.offset); - this.renderPoint(sprite.center); - this.renderPoint(sprite.topLeft); - this.renderPoint(sprite.topRight); - this.renderPoint(sprite.bottomLeft); - this.renderPoint(sprite.bottomRight); - - if (showText) - { - this.currentColor = color; - this.line('x: ' + Math.floor(sprite.topLeft.x) + ' y: ' + Math.floor(sprite.topLeft.y), sprite.topLeft.x, sprite.topLeft.y); - this.line('x: ' + Math.floor(sprite.topRight.x) + ' y: ' + Math.floor(sprite.topRight.y), sprite.topRight.x, sprite.topRight.y); - this.line('x: ' + Math.floor(sprite.bottomLeft.x) + ' y: ' + Math.floor(sprite.bottomLeft.y), sprite.bottomLeft.x, sprite.bottomLeft.y); - this.line('x: ' + Math.floor(sprite.bottomRight.x) + ' y: ' + Math.floor(sprite.bottomRight.y), sprite.bottomRight.x, sprite.bottomRight.y); - } - - this.stop(); - - }, - - /** - * Render Sound information, including decoded state, duration, volume and more. - * @method Phaser.Utils.Debug#renderSoundInfo - * @param {Phaser.Sound} sound - The sound object to debug. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderSoundInfo: function (sound, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255,255,255)'; - - this.start(x, y, color); - this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked); - this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback); - this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding); - this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying); - this.line('Time: ' + sound.currentTime); - this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute); - this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag); - - if (sound.currentMarker !== '') - { - this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration); - this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop); - this.line('Position: ' + sound.position); - } - - this.stop(); - - }, - - /** - * Render camera information including dimensions and location. - * @method Phaser.Utils.Debug#renderCameraInfo - * @param {Phaser.Camera} camera - Description. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderCameraInfo: function (camera, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255,255,255)'; - - this.start(x, y, color); - this.line('Camera (' + camera.width + ' x ' + camera.height + ')'); - this.line('X: ' + camera.x + ' Y: ' + camera.y); - this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height); - this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height); - this.stop(); - - }, - - /** - * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text. - * @method Phaser.Utils.Debug#renderDebug - * @param {Phaser.Pointer} pointer - Description. - * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up. - * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down. - * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false). - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderPointer: function (pointer, hideIfUp, downColor, upColor, color) { - - if (this.context == null || pointer == null) - { - return; - } - - if (typeof hideIfUp === 'undefined') { hideIfUp = false; } - downColor = downColor || 'rgba(0,255,0,0.5)'; - upColor = upColor || 'rgba(255,0,0,0.5)'; - color = color || 'rgb(255,255,255)'; - - if (hideIfUp == true && pointer.isUp == true) - { - return; - } - - this.start(pointer.x, pointer.y - 100, color); - this.context.beginPath(); - this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2); - - if (pointer.active) - { - this.context.fillStyle = downColor; - } - else - { - this.context.fillStyle = upColor; - } - - this.context.fill(); - this.context.closePath(); - - // Render the points - this.context.beginPath(); - this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y); - this.context.lineTo(pointer.position.x, pointer.position.y); - this.context.lineWidth = 2; - this.context.stroke(); - this.context.closePath(); - - // Render the text - // this.start(pointer.x, pointer.y - 100, color); - this.line('ID: ' + pointer.id + " Active: " + pointer.active); - this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY); - this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y); - this.line('Duration: ' + pointer.duration + " ms"); - this.stop(); - - }, - - /** - * Render Sprite Input Debug information. - * @method Phaser.Utils.Debug#renderSpriteInputInfo - * @param {Phaser.Sprite} sprite - The sprite to be rendered. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderSpriteInputInfo: function (sprite, x, y, color) { - - color = color || 'rgb(255,255,255)'; - - this.start(x, y, color); - this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')'); - this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1)); - this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0)); - this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0)); - this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut()); - this.stop(); - - }, - - /** - * Render Sprite collision. - * @method Phaser.Utils.Debug#renderSpriteCollision - * @param {Phaser.Sprite} sprite - The sprite to be rendered. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderSpriteCollision: function (sprite, x, y, color) { - - color = color || 'rgb(255,255,255)'; - - this.start(x, y, color); - this.line('Sprite Collision: (' + sprite.width + ' x ' + sprite.height + ')'); - this.line('left: ' + sprite.body.touching.left); - this.line('right: ' + sprite.body.touching.right); - this.line('up: ' + sprite.body.touching.up); - this.line('down: ' + sprite.body.touching.down); - this.line('velocity.x: ' + sprite.body.velocity.x); - this.line('velocity.y: ' + sprite.body.velocity.y); - this.stop(); - - }, - - /** - * Render debug information about the Input object. - * @method Phaser.Utils.Debug#renderInputInfo - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderInputInfo: function (x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255,255,0)'; - - this.start(x, y, color); - this.line('Input'); - this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y); - this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY); - this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1)); - this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY); - this.stop(); - - }, - - /** - * Render debug infos (including name, bounds info, position and some other properties) about the Sprite. - * @method Phaser.Utils.Debug#renderSpriteInfo - * @param {Phaser.Sprite} sprite - Description. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderSpriteInfo: function (sprite, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255, 255, 255)'; - - this.start(x, y, color); - - this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y); - this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1)); - this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1)); - this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera); - this.line('body x: ' + sprite.body.x.toFixed(1) + ' y: ' + sprite.body.y.toFixed(1)); - - // 0 = scaleX - // 1 = skewY - // 2 = translateX - // 3 = skewX - // 4 = scaleY - // 5 = translateY - - // this.line('id: ' + sprite._id); - // this.line('scale x: ' + sprite.worldTransform[0]); - // this.line('scale y: ' + sprite.worldTransform[4]); - // this.line('tx: ' + sprite.worldTransform[2]); - // this.line('ty: ' + sprite.worldTransform[5]); - // this.line('skew x: ' + sprite.worldTransform[3]); - // this.line('skew y: ' + sprite.worldTransform[1]); - this.line('deltaX: ' + sprite.body.deltaX()); - this.line('deltaY: ' + sprite.body.deltaY()); - // this.line('sdx: ' + sprite.deltaX()); - // this.line('sdy: ' + sprite.deltaY()); - - // this.line('inCamera: ' + this.game.renderer.spriteRenderer.inCamera(this.game.camera, sprite)); - this.stop(); - - }, - - /** - * Render the World Transform information of the given Sprite. - * @method Phaser.Utils.Debug#renderWorldTransformInfo - * @param {Phaser.Sprite} sprite - Description. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderWorldTransformInfo: function (sprite, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255, 255, 255)'; - - this.start(x, y, color); - - this.line('World Transform'); - this.line('skewX: ' + sprite.worldTransform[3]); - this.line('skewY: ' + sprite.worldTransform[1]); - this.line('scaleX: ' + sprite.worldTransform[0]); - this.line('scaleY: ' + sprite.worldTransform[4]); - this.line('transX: ' + sprite.worldTransform[2]); - this.line('transY: ' + sprite.worldTransform[5]); - this.stop(); - - }, - - /** - * Render the Local Transform information of the given Sprite. - * @method Phaser.Utils.Debug#renderLocalTransformInfo - * @param {Phaser.Sprite} sprite - Description. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderLocalTransformInfo: function (sprite, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255, 255, 255)'; - - this.start(x, y, color); - - this.line('Local Transform'); - this.line('skewX: ' + sprite.localTransform[3]); - this.line('skewY: ' + sprite.localTransform[1]); - this.line('scaleX: ' + sprite.localTransform[0]); - this.line('scaleY: ' + sprite.localTransform[4]); - this.line('transX: ' + sprite.localTransform[2]); - this.line('transY: ' + sprite.localTransform[5]); - this.stop(); - - }, - - renderSpriteCoords: function (sprite, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255, 255, 255)'; - - this.start(x, y, color); - - if (sprite.name) - { - this.line(sprite.name); - } - - this.line('x: ' + sprite.x); - this.line('y: ' + sprite.y); - this.line('pos x: ' + sprite.position.x); - this.line('pos y: ' + sprite.position.y); - this.line('local x: ' + sprite.localTransform[2]); - this.line('local y: ' + sprite.localTransform[5]); - this.line('t x: ' + sprite.worldTransform[2]); - this.line('t y: ' + sprite.worldTransform[5]); - this.line('world x: ' + sprite.world.x); - this.line('world y: ' + sprite.world.y); - - this.stop(); - - }, - - renderGroupInfo: function (group, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255, 255, 255)'; - - this.start(x, y, color); - - this.line('Group (size: ' + group.length + ')'); - this.line('x: ' + group.x); - this.line('y: ' + group.y); - - this.stop(); - - }, - - /** - * Renders Point coordinates in the given color. - * @method Phaser.Utils.Debug#renderPointInfo - * @param {Phaser.Point} sprite - Description. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string). - */ - renderPointInfo: function (point, x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255, 255, 255)'; - - this.start(x, y, color); - this.line('px: ' + point.x.toFixed(1) + ' py: ' + point.y.toFixed(1)); - this.stop(); - - }, - - /** - * Renders just the Sprite.body bounds. - * @method Phaser.Utils.Debug#renderSpriteBody - * @param {Phaser.Sprite} sprite - Description. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - */ - renderSpriteBody: function (sprite, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgba(255,0,255, 0.3)'; - - this.start(0, 0, color); - - this.context.fillStyle = color; - this.context.fillRect(sprite.body.screenX, sprite.body.screenY, sprite.body.width, sprite.body.height); - - this.stop(); - - }, - - /** - * Renders just the full Sprite bounds. - * @method Phaser.Utils.Debug#renderSpriteBounds - * @param {Phaser.Sprite} sprite - Description. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {boolean} [fill=false] - If false the bounds outline is rendered, if true the whole rectangle is rendered. - */ - renderSpriteBounds: function (sprite, color, fill) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255,0,255)'; - - if (typeof fill === 'undefined') { fill = false; } - - this.start(0, 0, color); - - if (fill) - { - this.context.fillStyle = color; - this.context.fillRect(sprite.bounds.x, sprite.bounds.y, sprite.bounds.width, sprite.bounds.height); - } - else - { - this.context.strokeStyle = color; - this.context.strokeRect(sprite.bounds.x, sprite.bounds.y, sprite.bounds.width, sprite.bounds.height); - this.context.stroke(); - } - - this.stop(); - - }, - - /** - * Renders a single pixel. - * @method Phaser.Utils.Debug#renderPixel - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - */ - renderPixel: function (x, y, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgba(0,255,0,1)'; - - this.start(); - this.context.fillStyle = color; - this.context.fillRect(x, y, 2, 2); - this.stop(); - - }, - - /** - * Renders a Point object. - * @method Phaser.Utils.Debug#renderPoint - * @param {Phaser.Point} point - The Point to render. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - */ - renderPoint: function (point, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgba(0,255,0,1)'; - - this.start(); - this.context.fillStyle = color; - this.context.fillRect(point.x, point.y, 4, 4); - this.stop(); - - }, - - /** - * Renders a Rectangle. - * @method Phaser.Utils.Debug#renderRectangle - * @param {Phaser.Rectangle} rect - The Rectangle to render. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - */ - renderRectangle: function (rect, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgba(0,255,0,0.3)'; - - this.start(); - this.context.fillStyle = color; - this.context.fillRect(rect.x, rect.y, rect.width, rect.height); - this.stop(); - - }, - - /** - * Renders a Circle. - * @method Phaser.Utils.Debug#renderCircle - * @param {Phaser.Circle} circle - The Circle to render. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - */ - renderCircle: function (circle, color) { - - if (this.context == null) - { - return; - } - - color = color || 'rgba(0,255,0,0.3)'; - - this.start(); - this.context.beginPath(); - this.context.fillStyle = color; - this.context.arc(circle.x, circle.y, circle.radius, 0, Math.PI * 2, false); - this.context.fill(); - this.context.closePath(); - this.stop(); - - }, - - /** - * Render text. - * @method Phaser.Utils.Debug#renderText - * @param {string} text - The line of text to draw. - * @param {number} x - X position of the debug info to be rendered. - * @param {number} y - Y position of the debug info to be rendered. - * @param {string} [color] - Color of the debug info to be rendered (format is css color string). - * @param {string} font - The font of text to draw. - */ - renderText: function (text, x, y, color, font) { - - if (this.context == null) - { - return; - } - - color = color || 'rgb(255,255,255)'; - font = font || '16px Courier'; - - this.start(); - this.context.font = font; - this.context.fillStyle = color; - this.context.fillText(text, x, y); - this.stop(); - - }, - - /** - * Dumps the Linked List to the console. - * - * @method Phaser.Utils.Debug#Phaser.LinkedList#dump - * @param {Phaser.LinkedList} list - The LinkedList to dump. - */ - dumpLinkedList: function (list) { - - var spacing = 20; - - var output = "\n" + Phaser.Utils.pad('Node', spacing) + "|" + Phaser.Utils.pad('Next', spacing) + "|" + Phaser.Utils.pad('Previous', spacing) + "|" + Phaser.Utils.pad('First', spacing) + "|" + Phaser.Utils.pad('Last', spacing); - console.log(output); - - var output = Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing) + "|" + Phaser.Utils.pad('----------', spacing); - console.log(output); - - var entity = list; - - var testObject = entity.last.next; - entity = entity.first; - - do - { - var name = entity.sprite.name || '*'; - var nameNext = '-'; - var namePrev = '-'; - var nameFirst = '-'; - var nameLast = '-'; - - if (entity.next) - { - nameNext = entity.next.sprite.name; - } - - if (entity.prev) - { - namePrev = entity.prev.sprite.name; - } - - if (entity.first) - { - nameFirst = entity.first.sprite.name; - } - - if (entity.last) - { - nameLast = entity.last.sprite.name; - } - - if (typeof nameNext === 'undefined') - { - nameNext = '-'; - } - - if (typeof namePrev === 'undefined') - { - namePrev = '-'; - } - - if (typeof nameFirst === 'undefined') - { - nameFirst = '-'; - } - - if (typeof nameLast === 'undefined') - { - nameLast = '-'; - } - - var output = Phaser.Utils.pad(name, spacing) + "|" + Phaser.Utils.pad(nameNext, spacing) + "|" + Phaser.Utils.pad(namePrev, spacing) + "|" + Phaser.Utils.pad(nameFirst, spacing) + "|" + Phaser.Utils.pad(nameLast, spacing); - console.log(output); - - entity = entity.next; - - } - while(entity != testObject) - - } - - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* A collection of methods useful for manipulating and comparing colors. -* -* @class Phaser.Color -*/ -Phaser.Color = { - - /** - * Given an alpha and 3 color values this will return an integer representation of it. - * - * @method Phaser.Color.getColor32 - * @static - * @param {number} alpha - The Alpha value (between 0 and 255). - * @param {number} red - The Red channel value (between 0 and 255). - * @param {number} green - The Green channel value (between 0 and 255). - * @param {number} blue - The Blue channel value (between 0 and 255). - * @returns {number} A native color value integer (format: 0xAARRGGBB). - */ - getColor32: function (alpha, red, green, blue) { - return alpha << 24 | red << 16 | green << 8 | blue; - }, - - /** - * Given 3 color values this will return an integer representation of it. - * - * @method Phaser.Color.getColor - * @static - * @param {number} red - The Red channel value (between 0 and 255). - * @param {number} green - The Green channel value (between 0 and 255). - * @param {number} blue - The Blue channel value (between 0 and 255). - * @returns {number} A native color value integer (format: 0xRRGGBB). - */ - getColor: function (red, green, blue) { - return red << 16 | green << 8 | blue; - }, - - /** - * Converts the given hex string into an integer color value. - * - * @method Phaser.Color.hexToRGB - * @static - * @param {string} h - The string hex color to convert. - * @returns {number} The rgb color value. - */ - hexToRGB: function (h) { - - var hex16 = (h.charAt(0) == "#") ? h.substring(1, 7) : h; - - if (hex16.length==3) - { - hex16 = hex16.charAt(0) + hex16.charAt(0) + hex16.charAt(1) + hex16.charAt(1) + hex16.charAt(2) + hex16.charAt(2); - } - - var red = parseInt(hex16.substring(0, 2), 16); - var green = parseInt(hex16.substring(2, 4), 16); - var blue = parseInt(hex16.substring(4, 6), 16); - - return red << 16 | green << 8 | blue; - - }, - - /** - * Returns a string containing handy information about the given color including string hex value, - * RGB format information and HSL information. Each section starts on a newline, 3 lines in total. - * - * @method Phaser.Color.getColorInfo - * @static - * @param {number} color - A color value in the format 0xAARRGGBB. - * @returns {string} String containing the 3 lines of information. - */ - getColorInfo: function (color) { - - var argb = Phaser.Color.getRGB(color); - var hsl = Phaser.Color.RGBtoHSV(color); - - // Hex format - var result = Phaser.Color.RGBtoHexstring(color) + "\n"; - - // RGB format - result = result.concat("Alpha: " + argb.alpha + " Red: " + argb.red + " Green: " + argb.green + " Blue: " + argb.blue) + "\n"; - - // HSL info - result = result.concat("Hue: " + hsl.hue + " Saturation: " + hsl.saturation + " Lightnes: " + hsl.lightness); - - return result; - - }, - - /** - * Return a string representation of the color in the format 0xAARRGGBB. - * - * @method Phaser.Color.RGBtoHexstring - * @static - * @param {number} color - The color to get the string representation for - * @returns {string} A string of length 10 characters in the format 0xAARRGGBB - */ - RGBtoHexstring: function (color) { - - var argb = Phaser.Color.getRGB(color); - - return "0x" + Phaser.Color.colorToHexstring(argb.alpha) + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue); - - }, - - /** - * Return a string representation of the color in the format #RRGGBB. - * - * @method Phaser.Color.RGBtoWebstring - * @static - * @param {number} color - The color to get the string representation for. - * @returns {string} A string of length 10 characters in the format 0xAARRGGBB. - */ - RGBtoWebstring: function (color) { - - var argb = Phaser.Color.getRGB(color); - - return "#" + Phaser.Color.colorToHexstring(argb.red) + Phaser.Color.colorToHexstring(argb.green) + Phaser.Color.colorToHexstring(argb.blue); - - }, - - /** - * Return a string containing a hex representation of the given color. - * - * @method Phaser.Color.colorToHexstring - * @static - * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255). - * @returns {string} A string of length 2 characters, i.e. 255 = FF, 0 = 00. - */ - colorToHexstring: function (color) { - - var digits = "0123456789ABCDEF"; - var lsd = color % 16; - var msd = (color - lsd) / 16; - var hexified = digits.charAt(msd) + digits.charAt(lsd); - return hexified; - - }, - - /** - * Interpolates the two given colours based on the supplied step and currentStep properties. - * @method Phaser.Color.interpolateColor - * @static - * @param {number} color1 - The first color value. - * @param {number} color2 - The second color value. - * @param {number} steps - The number of steps to run the interpolation over. - * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. - * @param {number} alpha - The alpha of the returned color. - * @returns {number} The interpolated color value. - */ - interpolateColor: function (color1, color2, steps, currentStep, alpha) { - - if (typeof alpha === "undefined") { alpha = 255; } - - var src1 = Phaser.Color.getRGB(color1); - var src2 = Phaser.Color.getRGB(color2); - var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red; - var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green; - var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue; - - return Phaser.Color.getColor32(alpha, r, g, b); - - }, - - /** - * Interpolates the two given colours based on the supplied step and currentStep properties. - * @method Phaser.Color.interpolateColorWithRGB - * @static - * @param {number} color - The first color value. - * @param {number} r - The red color value, between 0 and 0xFF (255). - * @param {number} g - The green color value, between 0 and 0xFF (255). - * @param {number} b - The blue color value, between 0 and 0xFF (255). - * @param {number} steps - The number of steps to run the interpolation over. - * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. - * @returns {number} The interpolated color value. - */ - interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) { - - var src = Phaser.Color.getRGB(color); - var or = (((r - src.red) * currentStep) / steps) + src.red; - var og = (((g - src.green) * currentStep) / steps) + src.green; - var ob = (((b - src.blue) * currentStep) / steps) + src.blue; - - return Phaser.Color.getColor(or, og, ob); - - }, - - /** - * Interpolates the two given colours based on the supplied step and currentStep properties. - * @method Phaser.Color.interpolateRGB - * @static - * @param {number} r1 - The red color value, between 0 and 0xFF (255). - * @param {number} g1 - The green color value, between 0 and 0xFF (255). - * @param {number} b1 - The blue color value, between 0 and 0xFF (255). - * @param {number} r2 - The red color value, between 0 and 0xFF (255). - * @param {number} g2 - The green color value, between 0 and 0xFF (255). - * @param {number} b2 - The blue color value, between 0 and 0xFF (255). - * @param {number} steps - The number of steps to run the interpolation over. - * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two. - * @returns {number} The interpolated color value. - */ - interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) { - - var r = (((r2 - r1) * currentStep) / steps) + r1; - var g = (((g2 - g1) * currentStep) / steps) + g1; - var b = (((b2 - b1) * currentStep) / steps) + b1; - - return Phaser.Color.getColor(r, g, b); - - }, - - /** - * Returns a random color value between black and white - * Set the min value to start each channel from the given offset. - * Set the max value to restrict the maximum color used per channel. - * - * @method Phaser.Color.getRandomColor - * @static - * @param {number} min - The lowest value to use for the color. - * @param {number} max - The highest value to use for the color. - * @param {number} alpha - The alpha value of the returning color (default 255 = fully opaque). - * @returns {number} 32-bit color value with alpha. - */ - getRandomColor: function (min, max, alpha) { - - if (typeof min === "undefined") { min = 0; } - if (typeof max === "undefined") { max = 255; } - if (typeof alpha === "undefined") { alpha = 255; } - - // Sanity checks - if (max > 255) { - return Phaser.Color.getColor(255, 255, 255); - } - - if (min > max) { - return Phaser.Color.getColor(255, 255, 255); - } - - var red = min + Math.round(Math.random() * (max - min)); - var green = min + Math.round(Math.random() * (max - min)); - var blue = min + Math.round(Math.random() * (max - min)); - - return Phaser.Color.getColor32(alpha, red, green, blue); - - }, - - /** - * Return the component parts of a color as an Object with the properties alpha, red, green, blue - * - * Alpha will only be set if it exist in the given color (0xAARRGGBB) - * - * @method Phaser.Color.getRGB - * @static - * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB). - * @returns {object} An Object with properties: alpha, red, green, blue. - */ - getRGB: function (color) { - - return { - alpha: color >>> 24, - red: color >> 16 & 0xFF, - green: color >> 8 & 0xFF, - blue: color & 0xFF - }; - - }, - - /** - * Returns a CSS friendly string value from the given color. - * @method Phaser.Color.getWebRGB - * @static - * @param {number} color - * @returns {string}A string in the format: 'rgba(r,g,b,a)' - */ - getWebRGB: function (color) { - - var alpha = (color >>> 24) / 255; - var red = color >> 16 & 0xFF; - var green = color >> 8 & 0xFF; - var blue = color & 0xFF; - - return 'rgba(' + red.toString() + ',' + green.toString() + ',' + blue.toString() + ',' + alpha.toString() + ')'; - - }, - - /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255. - * - * @method Phaser.Color.getAlpha - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). - */ - getAlpha: function (color) { - return color >>> 24; - }, - - /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1. - * - * @method Phaser.Color.getAlphaFloat - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)). - */ - getAlphaFloat: function (color) { - return (color >>> 24) / 255; - }, - - /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255. - * - * @method Phaser.Color.getRed - * @static - * @param {number} color In the format 0xAARRGGBB. - * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red). - */ - getRed: function (color) { - return color >> 16 & 0xFF; - }, - - /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255. - * - * @method Phaser.Color.getGreen - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green). - */ - getGreen: function (color) { - return color >> 8 & 0xFF; - }, - - /** - * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255. - * - * @method Phaser.Color.getBlue - * @static - * @param {number} color - In the format 0xAARRGGBB. - * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue). - */ - getBlue: function (color) { - return color & 0xFF; - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* @class Phaser.Physics -*/ -Phaser.Physics = {}; - -/** -* Arcade Physics constructor. -* -* @class Phaser.Physics.Arcade -* @classdesc Arcade Physics Constructor -* @constructor -* @param {Phaser.Game} game reference to the current game instance. -*/ -Phaser.Physics.Arcade = function (game) { - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = game; - - /** - * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity. - */ - this.gravity = new Phaser.Point; - - /** - * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds. - */ - this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height); - - /** - * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad. - */ - this.maxObjects = 10; - - /** - * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels. - */ - this.maxLevels = 4; - - /** - * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks. - */ - this.OVERLAP_BIAS = 4; - - /** - * @property {Phaser.QuadTree} quadTree - The world QuadTree. - */ - this.quadTree = new Phaser.QuadTree(this, this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels); - - /** - * @property {number} quadTreeID - The QuadTree ID. - */ - this.quadTreeID = 0; - - // Avoid gc spikes by caching these values for re-use - - /** - * @property {Phaser.Rectangle} _bounds1 - Internal cache var. - * @private - */ - this._bounds1 = new Phaser.Rectangle; - - /** - * @property {Phaser.Rectangle} _bounds2 - Internal cache var. - * @private - */ - this._bounds2 = new Phaser.Rectangle; - - /** - * @property {number} _overlap - Internal cache var. - * @private - */ - this._overlap = 0; - - /** - * @property {number} _maxOverlap - Internal cache var. - * @private - */ - this._maxOverlap = 0; - - /** - * @property {number} _velocity1 - Internal cache var. - * @private - */ - this._velocity1 = 0; - - /** - * @property {number} _velocity2 - Internal cache var. - * @private - */ - this._velocity2 = 0; - - /** - * @property {number} _newVelocity1 - Internal cache var. - * @private - */ - this._newVelocity1 = 0; - - /** - * @property {number} _newVelocity2 - Internal cache var. - * @private - */ - this._newVelocity2 = 0; - - /** - * @property {number} _average - Internal cache var. - * @private - */ - this._average = 0; - - /** - * @property {Array} _mapData - Internal cache var. - * @private - */ - this._mapData = []; - - /** - * @property {number} _mapTiles - Internal cache var. - * @private - */ - this._mapTiles = 0; - - /** - * @property {boolean} _result - Internal cache var. - * @private - */ - this._result = false; - - /** - * @property {number} _total - Internal cache var. - * @private - */ - this._total = 0; - - /** - * @property {number} _angle - Internal cache var. - * @private - */ - this._angle = 0; - - /** - * @property {number} _dx - Internal cache var. - * @private - */ - this._dx = 0; - - /** - * @property {number} _dy - Internal cache var. - * @private - */ - this._dy = 0; - -}; - -Phaser.Physics.Arcade.prototype = { - - /** - * Called automatically by a Physics body, it updates all motion related values on the Body. - * - * @method Phaser.Physics.Arcade#updateMotion - * @param {Phaser.Physics.Arcade.Body} The Body object to be updated. - */ - updateMotion: function (body) { - - // If you're wondering why the velocity is halved and applied twice, read this: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html - - // Rotation - this._velocityDelta = (this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity) * this.game.time.physicsElapsed * 0.5 * 60; - body.angularVelocity += this._velocityDelta; - body.rotation += (body.angularVelocity * this.game.time.physicsElapsed); - body.angularVelocity += this._velocityDelta; - - // Horizontal - this._velocityDelta = (this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x) - body.velocity.x) * this.game.time.physicsElapsed * 0.5 * 60; - body.velocity.x += this._velocityDelta; - body.x += (body.velocity.x * this.game.time.physicsElapsed); - body.velocity.x += this._velocityDelta; - - // Vertical - this._velocityDelta = (this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y) - body.velocity.y) * this.game.time.physicsElapsed * 0.5 * 60; - body.velocity.y += this._velocityDelta; - body.y += (body.velocity.y * this.game.time.physicsElapsed); - body.velocity.y += this._velocityDelta; - - }, - - /** - * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity. - * - * @method Phaser.Physics.Arcade#computeVelocity - * @param {number} axis - 1 for horizontal, 2 for vertical. - * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated. - * @param {number} velocity - Any component of velocity (e.g. 20). - * @param {number} acceleration - Rate at which the velocity is changing. - * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set. - * @param {number} mMax - An absolute value cap for the velocity. - * @return {number} The altered Velocity value. - */ - computeVelocity: function (axis, body, velocity, acceleration, drag, max) { - - max = max || 10000; - - if (axis == 1 && body.allowGravity) - { - velocity += this.gravity.x + body.gravity.x; - } - else if (axis == 2 && body.allowGravity) - { - velocity += this.gravity.y + body.gravity.y; - } - - if (acceleration !== 0) - { - velocity += acceleration * this.game.time.physicsElapsed; - } - else if (drag !== 0) - { - this._drag = drag * this.game.time.physicsElapsed; - - if (velocity - this._drag > 0) - { - velocity -= this._drag; - } - else if (velocity + this._drag < 0) - { - velocity += this._drag; - } - else - { - velocity = 0; - } - } - - if (velocity > max) - { - velocity = max; - } - else if (velocity < -max) - { - velocity = -max; - } - - return velocity; - - }, - - /** - * Called automatically by the core game loop. - * - * @method Phaser.Physics.Arcade#preUpdate - * @protected - */ - preUpdate: function () { - - // Clear the tree - this.quadTree.clear(); - - // Create our tree which all of the Physics bodies will add themselves to - this.quadTreeID = 0; - this.quadTree = new Phaser.QuadTree(this, this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels); - - }, - - /** - * Called automatically by the core game loop. - * - * @method Phaser.Physics.Arcade#postUpdate - * @protected - */ - postUpdate: function () { - - // Clear the tree ready for the next update - this.quadTree.clear(); - - }, - - /** - * Checks if two Sprite objects overlap. - * - * @method Phaser.Physics.Arcade#overlap - * @param {Phaser.Sprite} object1 - The first object to check. Can be an instance of Phaser.Sprite or anything that extends it. - * @param {Phaser.Sprite} object2 - The second object to check. Can be an instance of Phaser.Sprite or anything that extends it. - * @returns {boolean} true if the two objects overlap. - */ - overlap: function (object1, object2) { - - // Only test valid objects - if (object1 && object2 && object1.exists && object2.exists) - { - return (Phaser.Rectangle.intersects(object1.body, object2.body)); - } - - return false; - - }, - - /** - * Checks for collision between two game objects. The objects can be Sprites, Groups, Emitters or Tilemap Layers. - * You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions. - * The objects are also automatically separated. - * - * @method Phaser.Physics.Arcade#collide - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.Tilemap - * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.Tilemap} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.Tilemap - * @param {function} [collideCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you passed them to Collision.overlap. - * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collideCallback will only be called if processCallback returns true. - * @param {object} [callbackContext] - The context in which to run the callbacks. - * @returns {number} The number of collisions that were processed. - */ - collide: function (object1, object2, collideCallback, processCallback, callbackContext) { - - collideCallback = collideCallback || null; - processCallback = processCallback || null; - callbackContext = callbackContext || collideCallback; - - this._result = false; - this._total = 0; - - // Only collide valid objects - if (object1 && object2 && object1.exists && object2.exists) - { - // Can expand to support Buttons, Text, etc at a later date. For now these are the essentials. - - // SPRITES - if (object1.type == Phaser.SPRITE) - { - if (object2.type == Phaser.SPRITE) - { - this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER) - { - this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.TILEMAPLAYER) - { - this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext); - } - } - // GROUPS - else if (object1.type == Phaser.GROUP) - { - if (object2.type == Phaser.SPRITE) - { - this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER) - { - this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.TILEMAPLAYER) - { - this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext); - } - } - // TILEMAP LAYERS - else if (object1.type == Phaser.TILEMAPLAYER) - { - if (object2.type == Phaser.SPRITE) - { - this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER) - { - this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext); - } - } - // EMITTER - else if (object1.type == Phaser.EMITTER) - { - if (object2.type == Phaser.SPRITE) - { - this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.GROUP || object2.type == Phaser.EMITTER) - { - this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext); - } - else if (object2.type == Phaser.TILEMAPLAYER) - { - this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext); - } - } - } - - return (this._total > 0); - - }, - - /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer - * @private - */ - collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext) { - - this._mapData = tilemapLayer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true); - - if (this._mapData.length == 0) - { - return; - } - - for (var i = 0; i < this._mapData.length; i++) - { - if (this.separateTile(sprite.body, this._mapData[i])) - { - // They collided, is there a custom process callback? - if (processCallback) - { - if (processCallback.call(callbackContext, sprite, this._mapData[i])) - { - this._total++; - - if (collideCallback) - { - collideCallback.call(callbackContext, sprite, this._mapData[i]); - } - } - } - else - { - this._total++; - - if (collideCallback) - { - collideCallback.call(callbackContext, sprite, this._mapData[i]); - } - } - } - } - - }, - - /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer - * @private - */ - collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext) { - - if (group.length == 0) - { - return; - } - - if (group.length == 0) - { - return; - } - - if (group._container.first._iNext) - { - var currentNode = group._container.first._iNext; - - do - { - if (currentNode.exists) - { - this.collideSpriteVsTilemapLayer(currentNode, tilemapLayer, collideCallback, processCallback, callbackContext); - } - currentNode = currentNode._iNext; - } - while (currentNode != group._container.last._iNext); - } - - }, - - /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideSpriteVsSprite - * @private - */ - collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext) { - - this.separate(sprite1.body, sprite2.body); - - if (this._result) - { - // They collided, is there a custom process callback? - if (processCallback) - { - if (processCallback.call(callbackContext, sprite1, sprite2)) - { - this._total++; - - if (collideCallback) - { - collideCallback.call(callbackContext, sprite1, sprite2); - } - } - } - else - { - this._total++; - - if (collideCallback) - { - collideCallback.call(callbackContext, sprite1, sprite2); - } - } - } - - }, - - /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideSpriteVsGroup - * @private - */ - collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext) { - - if (group.length == 0) - { - return; - } - - // What is the sprite colliding with in the quadtree? - this._potentials = this.quadTree.retrieve(sprite); - - for (var i = 0, len = this._potentials.length; i < len; i++) - { - // We have our potential suspects, are they in this group? - if (this._potentials[i].sprite.group == group) - { - this.separate(sprite.body, this._potentials[i]); - - if (this._result && processCallback) - { - this._result = processCallback.call(callbackContext, sprite, this._potentials[i].sprite); - } - - if (this._result) - { - this._total++; - - if (collideCallback) - { - collideCallback.call(callbackContext, sprite, this._potentials[i].sprite); - } - } - } - } - - }, - - /** - * An internal function. Use Phaser.Physics.Arcade.collide instead. - * - * @method Phaser.Physics.Arcade#collideGroupVsGroup - * @private - */ - collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext) { - - if (group1.length == 0 || group2.length == 0) - { - return; - } - - if (group1._container.first._iNext) - { - var currentNode = group1._container.first._iNext; - - do - { - if (currentNode.exists) - { - this.collideSpriteVsGroup(currentNode, group2, collideCallback, processCallback, callbackContext); - } - currentNode = currentNode._iNext; - } - while (currentNode != group1._container.last._iNext); - } - - }, - - /** - * The core separation function to separate two physics bodies. - * @method Phaser.Physics.Arcade#separate - * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate. - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - separate: function (body1, body2) { - - this._result = (this.separateX(body1, body2) || this.separateY(body1, body2)); - - }, - - /** - * The core separation function to separate two physics bodies on the x axis. - * @method Phaser.Physics.Arcade#separateX - * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate. - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - separateX: function (body1, body2) { - - // Can't separate two immovable bodies - if (body1.immovable && body2.immovable) - { - return false; - } - - this._overlap = 0; - - // Check if the hulls actually overlap - if (Phaser.Rectangle.intersects(body1, body2)) - { - this._maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS; - - if (body1.deltaX() == 0 && body2.deltaX() == 0) - { - // They overlap but neither of them are moving - body1.embedded = true; - body2.embedded = true; - } - else if (body1.deltaX() > body2.deltaX()) - { - // Body1 is moving right and/or Body2 is moving left - this._overlap = body1.x + body1.width - body2.x; - - if ((this._overlap > this._maxOverlap) || body1.allowCollision.right == false || body2.allowCollision.left == false) - { - this._overlap = 0; - } - else - { - body1.touching.right = true; - body2.touching.left = true; - } - } - else if (body1.deltaX() < body2.deltaX()) - { - // Body1 is moving left and/or Body2 is moving right - this._overlap = body1.x - body2.width - body2.x; - - if ((-this._overlap > this._maxOverlap) || body1.allowCollision.left == false || body2.allowCollision.right == false) - { - this._overlap = 0; - } - else - { - body1.touching.left = true; - body2.touching.right = true; - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) - { - body1.overlapX = this._overlap; - body2.overlapX = this._overlap; - - if (body1.customSeparateX || body2.customSeparateX) - { - return true; - } - - this._velocity1 = body1.velocity.x; - this._velocity2 = body2.velocity.x; - - if (!body1.immovable && !body2.immovable) - { - this._overlap *= 0.5; - - body1.x = body1.x - this._overlap; - body2.x += this._overlap; - - this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1); - this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1); - this._average = (this._newVelocity1 + this._newVelocity2) * 0.5; - this._newVelocity1 -= this._average; - this._newVelocity2 -= this._average; - - body1.velocity.x = this._average + this._newVelocity1 * body1.bounce.x; - body2.velocity.x = this._average + this._newVelocity2 * body2.bounce.x; - } - else if (!body1.immovable) - { - body1.x = body1.x - this._overlap; - body1.velocity.x = this._velocity2 - this._velocity1 * body1.bounce.x; - } - else if (!body2.immovable) - { - body2.x += this._overlap; - body2.velocity.x = this._velocity1 - this._velocity2 * body2.bounce.x; - } - - return true; - } - } - - return false; - - }, - - /** - * The core separation function to separate two physics bodies on the y axis. - * @method Phaser.Physics.Arcade#separateY - * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate. - * @param {Phaser.Physics.Arcade.Body} body2 - The Body object to separate. - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - separateY: function (body1, body2) { - - // Can't separate two immovable or non-existing bodys - if (body1.immovable && body2.immovable) - { - return false; - } - - this._overlap = 0; - - // Check if the hulls actually overlap - if (Phaser.Rectangle.intersects(body1, body2)) - { - this._maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS; - - if (body1.deltaY() == 0 && body2.deltaY() == 0) - { - // They overlap but neither of them are moving - body1.embedded = true; - body2.embedded = true; - } - else if (body1.deltaY() > body2.deltaY()) - { - // Body1 is moving down and/or Body2 is moving up - this._overlap = body1.y + body1.height - body2.y; - - if ((this._overlap > this._maxOverlap) || body1.allowCollision.down == false || body2.allowCollision.up == false) - { - this._overlap = 0; - } - else - { - body1.touching.down = true; - body2.touching.up = true; - } - } - else if (body1.deltaY() < body2.deltaY()) - { - // Body1 is moving up and/or Body2 is moving down - this._overlap = body1.y - body2.height - body2.y; - - if ((-this._overlap > this._maxOverlap) || body1.allowCollision.up == false || body2.allowCollision.down == false) - { - this._overlap = 0; - } - else - { - body1.touching.up = true; - body2.touching.down = true; - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) - { - body1.overlapY = this._overlap; - body2.overlapY = this._overlap; - - if (body1.customSeparateY || body2.customSeparateY) - { - return true; - } - - this._velocity1 = body1.velocity.y; - this._velocity2 = body2.velocity.y; - - if (!body1.immovable && !body2.immovable) - { - this._overlap *= 0.5; - - body1.y = body1.y - this._overlap; - body2.y += this._overlap; - - this._newVelocity1 = Math.sqrt((this._velocity2 * this._velocity2 * body2.mass) / body1.mass) * ((this._velocity2 > 0) ? 1 : -1); - this._newVelocity2 = Math.sqrt((this._velocity1 * this._velocity1 * body1.mass) / body2.mass) * ((this._velocity1 > 0) ? 1 : -1); - this._average = (this._newVelocity1 + this._newVelocity2) * 0.5; - this._newVelocity1 -= this._average; - this._newVelocity2 -= this._average; - - body1.velocity.y = this._average + this._newVelocity1 * body1.bounce.y; - body2.velocity.y = this._average + this._newVelocity2 * body2.bounce.y; - } - else if (!body1.immovable) - { - body1.y = body1.y - this._overlap; - body1.velocity.y = this._velocity2 - this._velocity1 * body1.bounce.y; - - // This is special case code that handles things like horizontal moving platforms you can ride - if (body2.active && body2.moves && (body1.deltaY() > body2.deltaY())) - { - body1.x += body2.x - body2.lastX; - } - } - else if (!body2.immovable) - { - body2.y += this._overlap; - body2.velocity.y = this._velocity1 - this._velocity2 * body2.bounce.y; - - // This is special case code that handles things like horizontal moving platforms you can ride - if (body1.sprite.active && body1.moves && (body1.deltaY() < body2.deltaY())) - { - body2.x += body1.x - body1.lastX; - } - } - - return true; - } - - } - - return false; - - }, - - /** - * The core separation function to separate a physics body and a tile. - * @method Phaser.Physics.Arcade#separateTile - * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate. - * @param {Phaser.Tile} tile - The tile to collide against. - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - separateTile: function (body, tile) { - - this._result = (this.separateTileX(body, tile, true) || this.separateTileY(body, tile, true)); - - return this._result; - - }, - - /** - * The core separation function to separate a physics body and a tile on the x axis. - * @method Phaser.Physics.Arcade#separateTileX - * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate. - * @param {Phaser.Tile} tile - The tile to collide against. - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - separateTileX: function (body, tile, separate) { - - // Can't separate two immovable objects (tiles are always immovable) - if (body.immovable || body.deltaX() == 0 || Phaser.Rectangle.intersects(body.hullX, tile) == false) - { - return false; - } - - this._overlap = 0; - - // The hulls overlap, let's process it - // this._maxOverlap = body.deltaAbsX() + this.OVERLAP_BIAS; - - if (body.deltaX() < 0) - { - // Moving left - this._overlap = tile.right - body.hullX.x; - - // if ((this._overlap > this._maxOverlap) || body.allowCollision.left == false || tile.tile.collideRight == false) - if (body.allowCollision.left == false || tile.tile.collideRight == false) - { - this._overlap = 0; - } - else - { - body.touching.left = true; - } - } - else - { - // Moving right - this._overlap = body.hullX.right - tile.x; - - // if ((this._overlap > this._maxOverlap) || body.allowCollision.right == false || tile.tile.collideLeft == false) - if (body.allowCollision.right == false || tile.tile.collideLeft == false) - { - this._overlap = 0; - } - else - { - body.touching.right = true; - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) - { - if (separate) - { - if (body.deltaX() < 0) - { - body.x = body.x + this._overlap; - } - else - { - body.x = body.x - this._overlap; - } - - if (body.bounce.x == 0) - { - body.velocity.x = 0; - } - else - { - body.velocity.x = -body.velocity.x * body.bounce.x; - } - - body.updateHulls(); - } - - return true; - } - else - { - return false; - } - - }, - - /** - * The core separation function to separate a physics body and a tile on the x axis. - * @method Phaser.Physics.Arcade#separateTileY - * @param {Phaser.Physics.Arcade.Body} body1 - The Body object to separate. - * @param {Phaser.Tile} tile - The tile to collide against. - * @returns {boolean} Returns true if the bodies were separated, otherwise false. - */ - separateTileY: function (body, tile, separate) { - - // Can't separate two immovable objects (tiles are always immovable) - if (body.immovable || body.deltaY() == 0 || Phaser.Rectangle.intersects(body.hullY, tile) == false) - { - return false; - } - - this._overlap = 0; - - // The hulls overlap, let's process it - // this._maxOverlap = body.deltaAbsY() + this.OVERLAP_BIAS; - - if (body.deltaY() < 0) - { - // Moving up - this._overlap = tile.bottom - body.hullY.y; - - // if ((this._overlap > this._maxOverlap) || body.allowCollision.up == false || tile.tile.collideDown == false) - if (body.allowCollision.up == false || tile.tile.collideDown == false) - { - this._overlap = 0; - } - else - { - body.touching.up = true; - } - } - else - { - // Moving down - this._overlap = body.hullY.bottom - tile.y; - - // if ((this._overlap > this._maxOverlap) || body.allowCollision.down == false || tile.tile.collideUp == false) - if (body.allowCollision.down == false || tile.tile.collideUp == false) - { - this._overlap = 0; - } - else - { - body.touching.down = true; - } - } - - // Then adjust their positions and velocities accordingly (if there was any overlap) - if (this._overlap != 0) - { - if (separate) - { - if (body.deltaY() < 0) - { - body.y = body.y + this._overlap; - } - else - { - body.y = body.y - this._overlap; - } - - if (body.bounce.y == 0) - { - body.velocity.y = 0; - } - else - { - body.velocity.y = -body.velocity.y * body.bounce.y; - } - - body.updateHulls(); - } - - return true; - } - else - { - return false; - } - - }, - - /** - * Move the given display object towards the destination object at a steady velocity. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * - * @method Phaser.Physics.Arcade#moveToObject - * @param {any} displayObject - The display object to move. - * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - moveToObject: function (displayObject, destination, speed, maxTime) { - - if (typeof speed === 'undefined') { speed = 60; } - if (typeof maxTime === 'undefined') { maxTime = 0; } - - this._angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x); - - if (maxTime > 0) - { - // We know how many pixels we need to move, but how fast? - speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000); - } - - displayObject.body.velocity.x = Math.cos(this._angle) * speed; - displayObject.body.velocity.y = Math.sin(this._angle) * speed; - - return this._angle; - - }, - - /** - * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#moveToPointer - * @param {any} displayObject - The display object to move. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - moveToPointer: function (displayObject, speed, pointer, maxTime) { - - if (typeof speed === 'undefined') { speed = 60; } - pointer = pointer || this.game.input.activePointer; - if (typeof maxTime === 'undefined') { maxTime = 0; } - - this._angle = this.angleToPointer(displayObject, pointer); - - if (maxTime > 0) - { - // We know how many pixels we need to move, but how fast? - speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000); - } - - displayObject.body.velocity.x = Math.cos(this._angle) * speed; - displayObject.body.velocity.y = Math.sin(this._angle) * speed; - - return this._angle; - - }, - - /** - * Move the given display object towards the x/y coordinates at a steady velocity. - * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds. - * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all) - * - * @method Phaser.Physics.Arcade#moveToXY - * @param {any} displayObject - The display object to move. - * @param {number} x - The x coordinate to move towards. - * @param {number} y - The y coordinate to move towards. - * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec) - * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity. - */ - moveToXY: function (displayObject, x, y, speed, maxTime) { - - if (typeof speed === 'undefined') { speed = 60; } - if (typeof maxTime === 'undefined') { maxTime = 0; } - - this._angle = Math.atan2(y - displayObject.y, x - displayObject.x); - - if (maxTime > 0) - { - // We know how many pixels we need to move, but how fast? - speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000); - } - - displayObject.body.velocity.x = Math.cos(this._angle) * speed; - displayObject.body.velocity.y = Math.sin(this._angle) * speed; - - return this._angle; - - }, - - /** - * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object. - * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. - * - * @method Phaser.Physics.Arcade#velocityFromAngle - * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative) - * @param {number} [speed=60] - The speed it will move, in pixels per second sq. - * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. - * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. - */ - velocityFromAngle: function (angle, speed, point) { - - if (typeof speed === 'undefined') { speed = 60; } - point = point || new Phaser.Point; - - return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed)); - - }, - - /** - * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object. - * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. - * - * @method Phaser.Physics.Arcade#velocityFromRotation - * @param {number} rotation - The angle in radians. - * @param {number} [speed=60] - The speed it will move, in pixels per second sq. - * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity. - * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value. - */ - velocityFromRotation: function (rotation, speed, point) { - - if (typeof speed === 'undefined') { speed = 60; } - point = point || new Phaser.Point; - - return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed)); - - }, - - /** - * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object. - * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object. - * - * @method Phaser.Physics.Arcade#accelerationFromRotation - * @param {number} rotation - The angle in radians. - * @param {number} [speed=60] - The speed it will move, in pixels per second sq. - * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration. - * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value. - */ - accelerationFromRotation: function (rotation, speed, point) { - - if (typeof speed === 'undefined') { speed = 60; } - point = point || new Phaser.Point; - - return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed)); - - }, - - /** - * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) - * You must give a maximum speed value, beyond which the display object won't go any faster. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#accelerateToObject - * @param {any} displayObject - The display object to move. - * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties. - * @param {number} [speed=60] - The speed it will accelerate in pixels per second. - * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. - */ - accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) { - - if (typeof speed === 'undefined') { speed = 60; } - if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; } - if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; } - - this._angle = this.angleBetween(displayObject, destination); - - displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed); - displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); - - return this._angle; - - }, - - /** - * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.) - * You must give a maximum speed value, beyond which the display object won't go any faster. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#accelerateToPointer - * @param {any} displayObject - The display object to move. - * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer. - * @param {number} [speed=60] - The speed it will accelerate in pixels per second. - * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. - */ - accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) { - - if (typeof speed === 'undefined') { speed = 60; } - if (typeof pointer === 'undefined') { pointer = this.game.input.activePointer; } - if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; } - if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; } - - this._angle = this.angleToPointer(displayObject, pointer); - - displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed); - displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); - - return this._angle; - - }, - - /** - * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.) - * You must give a maximum speed value, beyond which the display object won't go any faster. - * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course. - * Note: The display object doesn't stop moving once it reaches the destination coordinates. - * - * @method Phaser.Physics.Arcade#accelerateToXY - * @param {any} displayObject - The display object to move. - * @param {number} x - The x coordinate to accelerate towards. - * @param {number} y - The y coordinate to accelerate towards. - * @param {number} [speed=60] - The speed it will accelerate in pixels per second. - * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach. - * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach. - * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory. - */ - accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) { - - if (typeof speed === 'undefined') { speed = 60; } - if (typeof xSpeedMax === 'undefined') { xSpeedMax = 1000; } - if (typeof ySpeedMax === 'undefined') { ySpeedMax = 1000; } - - this._angle = this.angleToXY(displayObject, x, y); - - displayObject.body.acceleration.setTo(Math.cos(this._angle) * speed, Math.sin(this._angle) * speed); - displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax); - - return this._angle; - - }, - - /** - * Find the distance between two display objects (like Sprites). - * - * @method Phaser.Physics.Arcade#distanceBetween - * @param {any} source - The Display Object to test from. - * @param {any} target - The Display Object to test to. - * @return {number} The distance between the source and target objects. - */ - distanceBetween: function (source, target) { - - this._dx = source.x - target.x; - this._dy = source.y - target.y; - - return Math.sqrt(this._dx * this._dx + this._dy * this._dy); - - }, - - /** - * Find the distance between a display object (like a Sprite) and the given x/y coordinates. - * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. - * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters() - * - * @method Phaser.Physics.Arcade#distanceToXY - * @param {any} displayObject - The Display Object to test from. - * @param {number} x - The x coordinate to move towards. - * @param {number} y - The y coordinate to move towards. - * @return {number} The distance between the object and the x/y coordinates. - */ - distanceToXY: function (displayObject, x, y) { - - this._dx = displayObject.x - x; - this._dy = displayObject.y - y; - - return Math.sqrt(this._dx * this._dx + this._dy * this._dy); - - }, - - /** - * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used. - * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed. - * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters() - * - * @method Phaser.Physics.Arcade#distanceToPointer - * @param {any} displayObject - The Display Object to test from. - * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. - * @return {number} The distance between the object and the Pointer. - */ - distanceToPointer: function (displayObject, pointer) { - - pointer = pointer || this.game.input.activePointer; - - this._dx = displayObject.x - pointer.x; - this._dy = displayObject.y - pointer.y; - - return Math.sqrt(this._dx * this._dx + this._dy * this._dy); - - }, - - /** - * Find the angle in radians between two display objects (like Sprites). - * - * @method Phaser.Physics.Arcade#angleBetween - * @param {any} source - The Display Object to test from. - * @param {any} target - The Display Object to test to. - * @return {number} The angle in radians between the source and target display objects. - */ - angleBetween: function (source, target) { - - this._dx = target.x - source.x; - this._dy = target.y - source.y; - - return Math.atan2(this._dy, this._dx); - - }, - - /** - * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate. - * - * @method Phaser.Physics.Arcade#angleToXY - * @param {any} displayObject - The Display Object to test from. - * @param {number} x - The x coordinate to get the angle to. - * @param {number} y - The y coordinate to get the angle to. - * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y - */ - angleToXY: function (displayObject, x, y) { - - this._dx = x - displayObject.x; - this._dy = y - displayObject.y; - - return Math.atan2(this._dy, this._dx); - - }, - - /** - * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account. - * - * @method Phaser.Physics.Arcade#angleToPointer - * @param {any} displayObject - The Display Object to test from. - * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used. - * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y - */ - angleToPointer: function (displayObject, pointer) { - - pointer = pointer || this.game.input.activePointer; - - this._dx = pointer.worldX - displayObject.x; - this._dy = pointer.worldY - displayObject.y; - - return Math.atan2(this._dy, this._dx); - - } - -}; - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than -* the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body. -* -* @class Phaser.Physics.Arcade.Body -* @classdesc Arcade Physics Body Constructor -* @constructor -* @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to. -*/ -Phaser.Physics.Arcade.Body = function (sprite) { - - /** - * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. - */ - this.sprite = sprite; - - /** - * @property {Phaser.Game} game - Local reference to game. - */ - this.game = sprite.game; - - /** - * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. - */ - this.offset = new Phaser.Point; - - /** - * @property {number} x - The x position of the physics body. - * @readonly - */ - this.x = sprite.x; - - /** - * @property {number} y - The y position of the physics body. - * @readonly - */ - this.y = sprite.y; - - /** - * @property {number} preX - The previous x position of the physics body. - * @readonly - */ - this.preX = sprite.x; - - /** - * @property {number} preY - The previous y position of the physics body. - * @readonly - */ - this.preY = sprite.y; - - /** - * @property {number} preRotation - The previous rotation of the physics body. - * @readonly - */ - this.preRotation = sprite.angle; - - /** - * @property {number} screenX - The x position of the physics body translated to screen space. - * @readonly - */ - this.screenX = sprite.x; - - /** - * @property {number} screenY - The y position of the physics body translated to screen space. - * @readonly - */ - this.screenY = sprite.y; - - /** - * @property {number} sourceWidth - The un-scaled original size. - * @readonly - */ - this.sourceWidth = sprite.currentFrame.sourceSizeW; - - /** - * @property {number} sourceHeight - The un-scaled original size. - * @readonly - */ - this.sourceHeight = sprite.currentFrame.sourceSizeH; - - /** - * @property {number} width - The calculated width of the physics body. - */ - this.width = sprite.currentFrame.sourceSizeW; - - /** - * @property .numInternal ID cache - */ - this.height = sprite.currentFrame.sourceSizeH; - - /** - * @property {number} halfWidth - The calculated width / 2 of the physics body. - */ - this.halfWidth = Math.floor(sprite.currentFrame.sourceSizeW / 2); - - /** - * @property {number} halfHeight - The calculated height / 2 of the physics body. - */ - this.halfHeight = Math.floor(sprite.currentFrame.sourceSizeH / 2); - - /** - * @property {Phaser.Point} center - The center coordinate of the Physics Body. - */ - this.center = new Phaser.Point(this.x + this.halfWidth, this.y + this.halfHeight); - - /** - * @property {number} _sx - Internal cache var. - * @private - */ - this._sx = sprite.scale.x; - - /** - * @property {number} _sy - Internal cache var. - * @private - */ - this._sy = sprite.scale.y; - - /** - * @property {Phaser.Point} velocity - The velocity in pixels per second sq. of the Body. - */ - this.velocity = new Phaser.Point; - - /** - * @property {Phaser.Point} acceleration - The velocity in pixels per second sq. of the Body. - */ - this.acceleration = new Phaser.Point; - - /** - * @property {Phaser.Point} drag - The drag applied to the motion of the Body. - */ - this.drag = new Phaser.Point; - - /** - * @property {Phaser.Point} gravity - A private Gravity setting for the Body. - */ - this.gravity = new Phaser.Point; - - /** - * @property {Phaser.Point} bounce - The elasticitiy of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity. - */ - this.bounce = new Phaser.Point; - - /** - * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach. - * @default - */ - this.maxVelocity = new Phaser.Point(10000, 10000); - - /** - * @property {number} angularVelocity - The angular velocity in pixels per second sq. of the Body. - * @default - */ - this.angularVelocity = 0; - - /** - * @property {number} angularAcceleration - The angular acceleration in pixels per second sq. of the Body. - * @default - */ - this.angularAcceleration = 0; - - /** - * @property {number} angularDrag - The angular drag applied to the rotation of the Body. - * @default - */ - this.angularDrag = 0; - - /** - * @property {number} maxAngular - The maximum angular velocity in pixels per second sq. that the Body can reach. - * @default - */ - this.maxAngular = 1000; - - /** - * @property {number} mass - The mass of the Body. - * @default - */ - this.mass = 1; - - /** - * @property {boolean} skipQuadTree - If the Body is an irregular shape you can set this to true to avoid it being added to the World quad tree. - * @default - */ - this.skipQuadTree = false; - - /** - * @property {Array} quadTreeIDs - Internal ID cache. - * @protected - */ - this.quadTreeIDs = []; - - /** - * @property {number} quadTreeIndex - Internal ID cache. - * @protected - */ - this.quadTreeIndex = -1; - - // Allow collision - - /** - * Set the allowCollision properties to control which directions collision is processed for this Body. - * For example allowCollision.up = false means it won't collide when the collision happened while moving up. - * @property {object} allowCollision - An object containing allowed collision. - */ - this.allowCollision = { none: false, any: true, up: true, down: true, left: true, right: true }; - - /** - * This object is populated with boolean values when the Body collides with another. - * touching.up = true means the collision happened to the top of this Body for example. - * @property {object} touching - An object containing touching results. - */ - this.touching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * This object is populated with previous touching values from the bodies previous collision. - * @property {object} wasTouching - An object containing previous touching results. - */ - this.wasTouching = { none: true, up: false, down: false, left: false, right: false }; - - /** - * @property {number} facing - A const reference to the direction the Body is traveling or facing. - * @default - */ - this.facing = Phaser.NONE; - - /** - * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies. - * @default - */ - this.immovable = false; - - /** - * @property {boolean} moves - Set to true to allow the Physics system to move this Body, other false to move it manually. - * @default - */ - this.moves = true; - - /** - * @property {number} rotation - The amount the Body is rotated. - * @default - */ - this.rotation = 0; - - /** - * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc) - * @default - */ - this.allowRotation = true; - - /** - * @property {boolean} allowGravity - Allow this Body to be influenced by the global Gravity? - * @default - */ - this.allowGravity = true; - - /** - * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate. - * Used in combination with your own collision processHandler you can create whatever type of collision response you need. - * @property {boolean} customSeparateX - Use a custom separation system or the built-in one? - * @default - */ - this.customSeparateX = false; - - /** - * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate. - * Used in combination with your own collision processHandler you can create whatever type of collision response you need. - * @property {boolean} customSeparateY - Use a custom separation system or the built-in one? - * @default - */ - this.customSeparateY = false; - - /** - * When this body collides with another, the amount of overlap is stored here. - * @property {number} overlapX - The amount of horizontal overlap during the collision. - */ - this.overlapX = 0; - - /** - * When this body collides with another, the amount of overlap is stored here. - * @property {number} overlapY - The amount of vertical overlap during the collision. - */ - this.overlapY = 0; - - /** - * @property {Phaser.Rectangle} hullX - The dynamically calculated hull used during collision. - */ - this.hullX = new Phaser.Rectangle(); - - /** - * @property {Phaser.Rectangle} hullY - The dynamically calculated hull used during collision. - */ - this.hullY = new Phaser.Rectangle(); - - /** - * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true. - * @property {boolean} embedded - Body embed value. - */ - this.embedded = false; - - /** - * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World. - * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? - */ - this.collideWorldBounds = false; - -}; - -Phaser.Physics.Arcade.Body.prototype = { - - /** - * Internal method. - * - * @method Phaser.Physics.Arcade#updateBounds - * @protected - */ - updateBounds: function (centerX, centerY, scaleX, scaleY) { - - if (scaleX != this._sx || scaleY != this._sy) - { - this.width = this.sourceWidth * scaleX; - this.height = this.sourceHeight * scaleY; - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - this._sx = scaleX; - this._sy = scaleY; - this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - } - - }, - - /** - * Internal method. - * - * @method Phaser.Physics.Arcade#preUpdate - * @protected - */ - preUpdate: function () { - - // Store and reset collision flags - this.wasTouching.none = this.touching.none; - this.wasTouching.up = this.touching.up; - this.wasTouching.down = this.touching.down; - this.wasTouching.left = this.touching.left; - this.wasTouching.right = this.touching.right; - - this.touching.none = true; - this.touching.up = false; - this.touching.down = false; - this.touching.left = false; - this.touching.right = false; - - this.embedded = false; - - this.screenX = (this.sprite.worldTransform[2] - (this.sprite.anchor.x * this.width)) + this.offset.x; - this.screenY = (this.sprite.worldTransform[5] - (this.sprite.anchor.y * this.height)) + this.offset.y; - - this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x; - this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y; - - this.preRotation = this.sprite.angle; - - this.x = this.preX; - this.y = this.preY; - this.rotation = this.preRotation; - - if (this.moves) - { - this.game.physics.updateMotion(this); - - if (this.collideWorldBounds) - { - this.checkWorldBounds(); - } - - this.updateHulls(); - } - - if (this.skipQuadTree == false && this.allowCollision.none == false && this.sprite.visible && this.sprite.alive) - { - this.quadTreeIDs = []; - this.quadTreeIndex = -1; - this.game.physics.quadTree.insert(this); - } - - }, - - /** - * Internal method. - * - * @method Phaser.Physics.Arcade#postUpdate - * @protected - */ - postUpdate: function () { - - if (this.deltaX() < 0) - { - this.facing = Phaser.LEFT; - } - else if (this.deltaX() > 0) - { - this.facing = Phaser.RIGHT; - } - - if (this.deltaY() < 0) - { - this.facing = Phaser.UP; - } - else if (this.deltaY() > 0) - { - this.facing = Phaser.DOWN; - } - - if (this.deltaX() !== 0 || this.deltaY() !== 0) - { - this.sprite.x += this.deltaX(); - this.sprite.y += this.deltaY(); - this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - } - - if (this.allowRotation) - { - this.sprite.angle += this.deltaZ(); - } - - }, - - /** - * Internal method. - * - * @method Phaser.Physics.Arcade#updateHulls - * @protected - */ - updateHulls: function () { - - this.hullX.setTo(this.x, this.preY, this.width, this.height); - this.hullY.setTo(this.preX, this.y, this.width, this.height); - - }, - - /** - * Internal method. - * - * @method Phaser.Physics.Arcade#checkWorldBounds - * @protected - */ - checkWorldBounds: function () { - - if (this.x < this.game.world.bounds.x) - { - this.x = this.game.world.bounds.x; - this.velocity.x *= -this.bounce.x; - } - else if (this.right > this.game.world.bounds.right) - { - this.x = this.game.world.bounds.right - this.width; - this.velocity.x *= -this.bounce.x; - } - - if (this.y < this.game.world.bounds.y) - { - this.y = this.game.world.bounds.y; - this.velocity.y *= -this.bounce.y; - } - else if (this.bottom > this.game.world.bounds.bottom) - { - this.y = this.game.world.bounds.bottom - this.height; - this.velocity.y *= -this.bounce.y; - } - - }, - - /** - * You can modify the size of the physics Body to be any dimension you need. - * So it could be smaller or larger than the parent Sprite. You can also control the x and y offset, which - * is the position of the Body relative to the top-left of the Sprite. - * - * @method Phaser.Physics.Arcade#setSize - * @param {number} width - The width of the Body. - * @param {number} height - The height of the Body. - * @param {number} offsetX - The X offset of the Body from the Sprite position. - * @param {number} offsetY - The Y offset of the Body from the Sprite position. - */ - setSize: function (width, height, offsetX, offsetY) { - - offsetX = offsetX || this.offset.x; - offsetY = offsetY || this.offset.y; - - this.sourceWidth = width; - this.sourceHeight = height; - this.width = this.sourceWidth * this._sx; - this.height = this.sourceHeight * this._sy; - this.halfWidth = Math.floor(this.width / 2); - this.halfHeight = Math.floor(this.height / 2); - this.offset.setTo(offsetX, offsetY); - - this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - - }, - - /** - * Resets all Body values (velocity, acceleration, rotation, etc) - * - * @method Phaser.Physics.Arcade#reset - */ - reset: function () { - - this.velocity.setTo(0, 0); - this.acceleration.setTo(0, 0); - - this.angularVelocity = 0; - this.angularAcceleration = 0; - this.preX = (this.sprite.world.x - (this.sprite.anchor.x * this.width)) + this.offset.x; - this.preY = (this.sprite.world.y - (this.sprite.anchor.y * this.height)) + this.offset.y; - this.preRotation = this.sprite.angle; - - this.x = this.preX; - this.y = this.preY; - this.rotation = this.preRotation; - - this.center.setTo(this.x + this.halfWidth, this.y + this.halfHeight); - - }, - - /** - * Returns the absolute delta x value. - * - * @method Phaser.Physics.Arcade.Body#deltaAbsX - * @return {number} The absolute delta value. - */ - deltaAbsX: function () { - return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); - }, - - /** - * Returns the absolute delta y value. - * - * @method Phaser.Physics.Arcade.Body#deltaAbsY - * @return {number} The absolute delta value. - */ - deltaAbsY: function () { - return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); - }, - - /** - * Returns the delta x value. The difference between Body.x now and in the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaX - * @return {number} The delta value. - */ - deltaX: function () { - return this.x - this.preX; - }, - - /** - * Returns the delta y value. The difference between Body.y now and in the previous step. - * - * @method Phaser.Physics.Arcade.Body#deltaY - * @return {number} The delta value. - */ - deltaY: function () { - return this.y - this.preY; - }, - - deltaZ: function () { - return this.rotation - this.preRotation; - } - -}; - -/** -* @name Phaser.Physics.Arcade.Body#bottom -* @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height) -*/ -Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", { - - /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @return {number} - **/ - get: function () { - return this.y + this.height; - }, - - /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @param {number} value - **/ - set: function (value) { - - if (value <= this.y) - { - this.height = 0; - } - else - { - this.height = (this.y - value); - } - - } - -}); - -/** -* @name Phaser.Physics.Arcade.Body#right -* @property {number} right - The right value of this Body (same as Body.x + Body.width) -*/ -Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", { - - /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {number} - **/ - get: function () { - return this.x + this.width; - }, - - /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @param {number} value - **/ - set: function (value) { - - if (value <= this.x) - { - this.width = 0; - } - else - { - this.width = this.x + value; - } - - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it. -* -* @class Phaser.Particles -* @classdesc Phaser Particles -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -*/ -Phaser.Particles = function (game) { - - /** - * @property {Description} emitters - Description. - */ - this.emitters = {}; - - /** - * @property {number} ID - Description. - * @default - */ - this.ID = 0; - -}; - -Phaser.Particles.prototype = { - - /** - * Adds a new Particle Emitter to the Particle Manager. - * @method Phaser.Particles#add - * @param {Phaser.Emitter} emitter - Description. - * @return {Phaser.Emitter} The emitter that was added. - */ - add: function (emitter) { - - this.emitters[emitter.name] = emitter; - - return emitter; - - }, - - /** - * Removes an existing Particle Emitter from the Particle Manager. - * @method Phaser.Particles#remove - * @param {Phaser.Emitter} emitter - The emitter to remove. - */ - remove: function (emitter) { - - delete this.emitters[emitter.name]; - - }, - - /** - * Called by the core game loop. Updates all Emitters who have their exists value set to true. - * @method Phaser.Particles#update - * @protected - */ - update: function () { - - for (var key in this.emitters) - { - if (this.emitters[key].exists) - { - this.emitters[key].update(); - } - } - - } - -}; -Phaser.Particles.Arcade = {} -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -*/ - -/** -* Phaser - ArcadeEmitter -* -* @class Phaser.Particles.Arcade.Emitter -* @classdesc Emitter is a lightweight particle emitter. It can be used for one-time explosions or for -* continuous effects like rain and fire. All it really does is launch Particle objects out -* at set intervals, and fixes their positions and velocities accorindgly. -* @constructor -* @extends Phaser.Group -* @param {Phaser.Game} game - Current game instance. -* @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from. -* @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from. -* @param {number} [maxParticles=50] - The total number of particles in this emitter.. -*/ - -Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) { - - /** - * The total number of particles in this emitter. - * @property {number} maxParticles - The total number of particles in this emitter.. - * @default - */ - this.maxParticles = maxParticles || 50; - - Phaser.Group.call(this, game); - - /** - * @property {string} name - Description. - */ - this.name = 'emitter' + this.game.particles.ID++; - - /** - * @property {Description} type - Description. - */ - this.type = Phaser.EMITTER; - - /** - * @property {number} x - The X position of the top left corner of the emitter in world space. - * @default - */ - this.x = 0; - - /** - * @property {number} y - The Y position of the top left corner of emitter in world space. - * @default - */ - this.y = 0; - - /** - * @property {number} width - The width of the emitter. Particles can be randomly generated from anywhere within this box. - * @default - */ - this.width = 1; - - /** - * @property {number} height - The height of the emitter. Particles can be randomly generated from anywhere within this box. - * @default - */ - this.height = 1; - - /** - * The minimum possible velocity of a particle. - * The default value is (-100,-100). - * @property {Phaser.Point} minParticleSpeed - */ - this.minParticleSpeed = new Phaser.Point(-100, -100); - - /** - * The maximum possible velocity of a particle. - * The default value is (100,100). - * @property {Phaser.Point} maxParticleSpeed - */ - this.maxParticleSpeed = new Phaser.Point(100, 100); - - /** - * The minimum possible scale of a particle. - * The default value is 1. - * @property {number} minParticleScale - * @default - */ - this.minParticleScale = 1; - - /** - * The maximum possible scale of a particle. - * The default value is 1. - * @property {number} maxParticleScale - * @default - */ - this.maxParticleScale = 1; - - /** - * The minimum possible angular velocity of a particle. The default value is -360. - * @property {number} minRotation - * @default - */ - this.minRotation = -360; - - /** - * The maximum possible angular velocity of a particle. The default value is 360. - * @property {number} maxRotation - * @default - */ - this.maxRotation = 360; - - /** - * Sets the gravity.y of each particle to this value on launch. - * @property {number} gravity - * @default - */ - this.gravity = 2; - - /** - * Set your own particle class type here. - * @property {Description} particleClass - * @default - */ - this.particleClass = null; - - /** - * The X and Y drag component of particles launched from the emitter. - * @property {Phaser.Point} particleDrag - */ - this.particleDrag = new Phaser.Point(); - - /** - * The angular drag component of particles launched from the emitter if they are rotating. - * @property {number} angularDrag - * @default - */ - this.angularDrag = 0; - - /** - * How often a particle is emitted in ms (if emitter is started with Explode == false). - * @property {boolean} frequency - * @default - */ - this.frequency = 100; - - /** - * How long each particle lives once it is emitted in ms. Default is 2 seconds. - * Set lifespan to 'zero' for particles to live forever. - * @property {number} lifespan - * @default - */ - this.lifespan = 2000; - - /** - * How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce. - * @property {Phaser.Point} bounce - */ - this.bounce = new Phaser.Point(); - - /** - * Internal helper for deciding how many particles to launch. - * @property {number} _quantity - * @private - * @default - */ - this._quantity = 0; - - /** - * Internal helper for deciding when to launch particles or kill them. - * @property {number} _timer - * @private - * @default - */ - this._timer = 0; - - /** - * Internal counter for figuring out how many particles to launch. - * @property {number} _counter - * @private - * @default - */ - this._counter = 0; - - /** - * Internal helper for the style of particle emission (all at once, or one at a time). - * @property {boolean} _explode - * @private - * @default - */ - this._explode = true; - - /** - * Determines whether the emitter is currently emitting particles. - * It is totally safe to directly toggle this. - * @property {boolean} on - * @default - */ - this.on = false; - - /** - * Determines whether the emitter is being updated by the core game loop. - * @property {boolean} exists - * @default - */ - this.exists = true; - - /** - * The point the particles are emitted from. - * Emitter.x and Emitter.y control the containers location, which updates all current particles - * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. - * @property {boolean} emitX - */ - this.emitX = x; - - /** - * The point the particles are emitted from. - * Emitter.x and Emitter.y control the containers location, which updates all current particles - * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position. - * @property {boolean} emitY - */ - this.emitY = y; - -}; - -Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype); -Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter; - -/** -* Called automatically by the game loop, decides when to launch particles and when to "die". -* @method Phaser.Particles.Arcade.Emitter#update -*/ -Phaser.Particles.Arcade.Emitter.prototype.update = function () { - - if (this.on) - { - if (this._explode) - { - this._counter = 0; - - do - { - this.emitParticle(); - this._counter++; - } - while (this._counter < this._quantity); - - this.on = false; - } - else - { - if (this.game.time.now >= this._timer) - { - this.emitParticle(); - - this._counter++; - - if (this._quantity > 0) - { - if (this._counter >= this._quantity) - { - this.on = false; - } - } - - this._timer = this.game.time.now + this.frequency; - } - } - } - -} - -/** -* This function generates a new array of particle sprites to attach to the emitter. -* -* @method Phaser.Particles.Arcade.Emitter#makeParticles -* @param {Description} keys - Description. -* @param {number} frames - Description. -* @param {number} quantity - The number of particles to generate when using the "create from image" option. -* @param {number} collide - Description. -* @param {boolean} collideWorldBounds - Description. -* @return This Emitter instance (nice for chaining stuff together, if you're into that). -*/ -Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) { - - if (typeof frames == 'undefined') - { - frames = 0; - } - - quantity = quantity || this.maxParticles; - collide = collide || 0; - - if (typeof collideWorldBounds == 'undefined') - { - collideWorldBounds = false; - } - - var particle; - var i = 0; - var rndKey = keys; - var rndFrame = 0; - - while (i < quantity) - { - if (this.particleClass == null) - { - if (typeof keys == 'object') - { - rndKey = this.game.rnd.pick(keys); - } - - if (typeof frames == 'object') - { - rndFrame = this.game.rnd.pick(frames); - } - - particle = new Phaser.Sprite(this.game, 0, 0, rndKey, rndFrame); - } - else - { - // particle = new this.particleClass(this.game); - } - - if (collide > 0) - { - particle.body.allowCollision.any = true; - particle.body.allowCollision.none = false; - } - else - { - particle.body.allowCollision.none = true; - } - - particle.body.collideWorldBounds = collideWorldBounds; - - particle.exists = false; - particle.visible = false; - - // Center the origin for rotation assistance - particle.anchor.setTo(0.5, 0.5); - - this.add(particle); - - i++; - } - - return this; -} - -/** - * Call this function to turn off all the particles and the emitter. - * @method Phaser.Particles.Arcade.Emitter#kill - */ -Phaser.Particles.Arcade.Emitter.prototype.kill = function () { - - this.on = false; - this.alive = false; - this.exists = false; - -} - -/** - * Handy for bringing game objects "back to life". Just sets alive and exists back to true. - * In practice, this is most often called by Object.reset(). - * @method Phaser.Particles.Arcade.Emitter#revive - */ -Phaser.Particles.Arcade.Emitter.prototype.revive = function () { - - this.alive = true; - this.exists = true; - -} - -/** - * Call this function to start emitting particles. - * @method Phaser.Particles.Arcade.Emitter#start - * @param {boolean} explode - Whether the particles should all burst out at once. - * @param {number} lifespan - How long each particle lives once emitted. 0 = forever. - * @param {number} frequency - Ignored if Explode is set to true. Frequency is how often to emit a particle in ms. - * @param {number} quantity - How many particles to launch. 0 = "all of the particles". - */ -Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity) { - - if (typeof explode !== 'boolean') - { - explode = true; - } - - lifespan = lifespan || 0; - - // How many ms between emissions? - frequency = frequency || 250; - - // Total number of particles to emit - quantity = quantity || 0; - - this.revive(); - - this.visible = true; - this.on = true; - - this._explode = explode; - this.lifespan = lifespan; - this.frequency = frequency; - - if (explode) - { - this._quantity = quantity; - } - else - { - this._quantity += quantity; - } - - this._counter = 0; - this._timer = this.game.time.now + frequency; - -} - -/** - * This function can be used both internally and externally to emit the next particle. - * @method Phaser.Particles.Arcade.Emitter#emitParticle - */ -Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function () { - - var particle = this.getFirstExists(false); - - if (particle == null) - { - return; - } - - if (this.width > 1 || this.height > 1) - { - particle.reset(this.game.rnd.integerInRange(this.left, this.right), this.game.rnd.integerInRange(this.top, this.bottom)); - } - else - { - particle.reset(this.emitX, this.emitY); - } - - particle.lifespan = this.lifespan; - - particle.body.bounce.setTo(this.bounce.x, this.bounce.y); - - if (this.minParticleSpeed.x != this.maxParticleSpeed.x) - { - particle.body.velocity.x = this.game.rnd.integerInRange(this.minParticleSpeed.x, this.maxParticleSpeed.x); - } - else - { - particle.body.velocity.x = this.minParticleSpeed.x; - } - - if (this.minParticleSpeed.y != this.maxParticleSpeed.y) - { - particle.body.velocity.y = this.game.rnd.integerInRange(this.minParticleSpeed.y, this.maxParticleSpeed.y); - } - else - { - particle.body.velocity.y = this.minParticleSpeed.y; - } - - particle.body.gravity.y = this.gravity; - - if (this.minRotation != this.maxRotation) - { - particle.body.angularVelocity = this.game.rnd.integerInRange(this.minRotation, this.maxRotation); - } - else - { - particle.body.angularVelocity = this.minRotation; - } - - if (this.minParticleScale !== 1 || this.maxParticleScale !== 1) - { - var scale = this.game.rnd.realInRange(this.minParticleScale, this.maxParticleScale); - particle.scale.setTo(scale, scale); - } - - particle.body.drag.x = this.particleDrag.x; - particle.body.drag.y = this.particleDrag.y; - particle.body.angularDrag = this.angularDrag; - -} - -/** -* A more compact way of setting the width and height of the emitter. -* @method Phaser.Particles.Arcade.Emitter#setSize -* @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions). -* @param {number} height - The desired height of the emitter. -*/ -Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) { - - this.width = width; - this.height = height; - -} - -/** -* A more compact way of setting the X velocity range of the emitter. -* @method Phaser.Particles.Arcade.Emitter#setXSpeed -* @param {number} min - The minimum value for this range. -* @param {number} max - The maximum value for this range. -*/ -Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) { - - min = min || 0; - max = max || 0; - - this.minParticleSpeed.x = min; - this.maxParticleSpeed.x = max; - -} - -/** -* A more compact way of setting the Y velocity range of the emitter. -* @method Phaser.Particles.Arcade.Emitter#setYSpeed -* @param {number} min - The minimum value for this range. -* @param {number} max - The maximum value for this range. -*/ -Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) { - - min = min || 0; - max = max || 0; - - this.minParticleSpeed.y = min; - this.maxParticleSpeed.y = max; - -} - -/** -* A more compact way of setting the angular velocity constraints of the emitter. -* @method Phaser.Particles.Arcade.Emitter#setRotation -* @param {number} min - The minimum value for this range. -* @param {number} max - The maximum value for this range. -*/ -Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) { - - min = min || 0; - max = max || 0; - - this.minRotation = min; - this.maxRotation = max; - -} - -/** -* Change the emitter's midpoint to match the midpoint of a Object. -* @method Phaser.Particles.Arcade.Emitter#at -* @param {object} object - The Object that you want to sync up with. -*/ -Phaser.Particles.Arcade.Emitter.prototype.at = function (object) { - - this.emitX = object.center.x; - this.emitY = object.center.y; - -} - -/** -* The emitters alpha value. -* @name Phaser.Particles.Arcade.Emitter#alpha -* @property {number} alpha - Gets or sets the alpha value of the Emitter. -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "alpha", { - - get: function () { - return this._container.alpha; - }, - - set: function (value) { - this._container.alpha = value; - } - -}); - -/** -* The emitter visible state. -* @name Phaser.Particles.Arcade.Emitter#visible -* @property {boolean} visible - Gets or sets the Emitter visible state. -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "visible", { - - get: function () { - return this._container.visible; - }, - - set: function (value) { - this._container.visible = value; - } - -}); - -/** -* @name Phaser.Particles.Arcade.Emitter#x -* @property {number} x - Gets or sets the x position of the Emitter. -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", { - - get: function () { - return this.emitX; - }, - - set: function (value) { - this.emitX = value; - } - -}); - -/** -* @name Phaser.Particles.Arcade.Emitter#y -* @property {number} y - Gets or sets the y position of the Emitter. -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", { - - get: function () { - return this.emitY; - }, - - set: function (value) { - this.emitY = value; - } - -}); - -/** -* @name Phaser.Particles.Arcade.Emitter#left -* @property {number} left - Gets the left position of the Emitter. -* @readonly -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", { - - get: function () { - return Math.floor(this.x - (this.width / 2)); - } - -}); - -/** -* @name Phaser.Particles.Arcade.Emitter#right -* @property {number} right - Gets the right position of the Emitter. -* @readonly -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", { - - get: function () { - return Math.floor(this.x + (this.width / 2)); - } - -}); - -/** -* @name Phaser.Particles.Arcade.Emitter#top -* @property {number} top - Gets the top position of the Emitter. -* @readonly -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", { - - get: function () { - return Math.floor(this.y - (this.height / 2)); - } - -}); - -/** -* @name Phaser.Particles.Arcade.Emitter#bottom -* @property {number} bottom - Gets the bottom position of the Emitter. -* @readonly -*/ -Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", { - - get: function () { - return Math.floor(this.y + (this.height / 2)); - } - -}); - -/** -* @author Richard Davey -* @copyright 2013 Photon Storm Ltd. -* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} -* @module Phaser.Tile -*/ - - -/** -* Create a new Tile. -* -* @class Phaser.Tile -* @classdesc A Tile is a single representation of a tile within a Tilemap. -* @constructor -* @param {Phaser.Game} game - A reference to the currently running game. -* @param {Tilemap} tilemap - The tilemap this tile belongs to. -* @param {number} index - The index of this tile type in the core map data. -* @param {number} width - Width of the tile. -* @param {number} height - Height of the tile. -*/ -Phaser.Tile = function (tileset, index, x, y, width, height) { - - /** - * @property {string} tileset - The tileset this tile belongs to. - */ - this.tileset = tileset; - - /** - * @property {number} index - The index of this tile within the tileset. - */ - this.index = index; - - /** - * @property {number} width - The width of the tile in pixels. - */ - this.width = width; - - /** - * @property {number} height - The height of the tile in pixels. - */ - this.height = height; - - /** - * @property {number} x - The top-left corner of the tile within the tileset. - */ - this.x = x; - - /** - * @property {number} y - The top-left corner of the tile within the tileset. - */ - this.y = y; - - // Any extra meta data info we need here - - /** - * @property {number} mass - The virtual mass of the tile. - * @default - */ - this.mass = 1.0; - - /** - * @property {boolean} collideNone - Indicating this Tile doesn't collide at all. - * @default - */ - this.collideNone = true; - - /** - * @property {boolean} collideLeft - Indicating collide with any object on the left. - * @default - */ - this.collideLeft = false; - - /** - * @property {boolean} collideRight - Indicating collide with any object on the right. - * @default - */ - this.collideRight = false; - - /** - * @property {boolean} collideUp - Indicating collide with any object on the top. - * @default - */ - this.collideUp = false; - - /** - * @property {boolean} collideDown - Indicating collide with any object on the bottom. - * @default - */ - this.collideDown = false; - - /** - * @property {boolean} separateX - Enable separation at x-axis. - * @default - */ - this.separateX = true; - - /** - * @property {boolean} separateY - Enable separation at y-axis. - * @default - */ - this.separateY = true; - - /** - * @property {boolean} collisionCallback - Tilemap collision callback. - * @default - */ - this.collisionCallback = null; - - /** - * @property {boolean} collisionCallback - Tilemap collision callback. - * @default - */ - this.collisionCallbackContext = this; - -}; - -Phaser.Tile.prototype = { - - /** - * Set callback to be called when this tilemap collides. - * - * @method Phaser.Tilemap.prototype.setCollisionCallback - * @param {Function} callback - Callback function. - * @param {object} context - Callback will be called with this context. - */ - setCollisionCallback: function (callback, context) { - - this.collisionCallbackContext = context; - this.collisionCallback = callback; - - }, - - /** - * Clean up memory. - * @method destroy - */ - destroy: function () { - - this.tileset = null; - - }, - - /** - * Set collision configs. - * @method setCollision - * @param {boolean} left - Indicating collide with any object on the left. - * @param {boolean} right - Indicating collide with any object on the right. - * @param {boolean} up - Indicating collide with any object on the top. - * @param {boolean} down - Indicating collide with any object on the bottom. - * @param {boolean} reset - Description. - * @param {boolean} separateX - Separate at x-axis. - * @param {boolean} separateY - Separate at y-axis. - */ - setCollision: function (left, right, up, down) { - - this.collideLeft = left; - this.collideRight = right; - this.collideUp = up; - this.collideDown = down; - - if (left || right || up || down) - { - this.collideNone = false; - } - else - { - this.collideNone = true; - } - - }, - - /** - * Reset collision status flags. - * @method resetCollision - */ - resetCollision: function () { - - this.collideNone = true; - this.collideLeft = false; - this.collideRight = false; - this.collideUp = false; - this.collideDown = false; - - } - -}; - -Object.defineProperty(Phaser.Tile.prototype, "bottom", { - - /** - * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property. - * @method bottom - * @return {number} - **/ - get: function () { - return this.y + this.height; - } - -}); - -Object.defineProperty(Phaser.Tile.prototype, "right", { - - /** - * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties. - * However it does affect the width property. - * @method right - * @return {number} - **/ - get: function () { - return this.x + this.width; - } - -}); - -Phaser.Tilemap = function (game, key) { - - /** - * @property {Phaser.Game} game - Description. - */ - this.game = game; - - /** - * @property {array} layers - Description. - */ - this.layers; - - if (typeof key === 'string') - { - this.key = key; - - this.layers = game.cache.getTilemapData(key).layers; - this.calculateIndexes(); - } - else - { - this.layers = []; - } - - this.currentLayer = 0; - - this.debugMap = []; - - this.dirty = false; - - this._results = []; - this._tempA = 0; - this._tempB = 0; - -}; - -Phaser.Tilemap.CSV = 0; -Phaser.Tilemap.TILED_JSON = 1; - -Phaser.Tilemap.prototype = { - - create: function (name, width, height) { - - var data = []; - - for (var y = 0; y < height; y++) - { - data[y] = []; - - for (var x = 0; x < width; x++) - { - data[y][x] = 0; - } - } - - this.currentLayer = this.layers.push({ - - name: name, - width: width, - height: height, - alpha: 1, - visible: true, - tileMargin: 0, - tileSpacing: 0, - format: Phaser.Tilemap.CSV, - data: data, - indexes: [] - - }); - - this.dirty = true; - - }, - - calculateIndexes: function () { - - for (var layer = 0; layer < this.layers.length; layer++) - { - this.layers[layer].indexes = []; - - for (var y = 0; y < this.layers[layer].height ; y++) - { - for (var x = 0; x < this.layers[layer].width; x++) - { - var idx = this.layers[layer].data[y][x]; - - if (this.layers[layer].indexes.indexOf(idx) === -1) - { - this.layers[layer].indexes.push(idx); - } - } - } - } - - }, - - setLayer: function (layer) { - - if (this.layers[layer]) - { - this.currentLayer = layer; - } - - }, - - /** - * Set a specific tile with its x and y in tiles. - * @method putTile - * @param {number} x - X position of this tile. - * @param {number} y - Y position of this tile. - * @param {number} index - The index of this tile type in the core map data. - */ - putTile: function (index, x, y, layer) { - - if (typeof layer === "undefined") { layer = this.currentLayer; } - - if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) - { - this.layers[layer].data[y][x] = index; - } - - this.dirty = true; - - }, - - getTile: function (x, y, layer) { - - if (typeof layer === "undefined") { layer = this.currentLayer; } - - if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) - { - return this.layers[layer].data[y][x]; - } - - }, - - getTileWorldXY: function (x, y, tileWidth, tileHeight, layer) { - - if (typeof layer === "undefined") { layer = this.currentLayer; } - - x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; - y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; - - if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) - { - return this.layers[layer].data[y][x]; - } - - }, - - /** - * Set a specific tile with its x and y in tiles. - * @method putTileWorldXY - * @param {number} x - X position of this tile in world coordinates. - * @param {number} y - Y position of this tile in world coordinates. - * @param {number} index - The index of this tile type in the core map data. - */ - putTileWorldXY: function (index, x, y, tileWidth, tileHeight, layer) { - - x = this.game.math.snapToFloor(x, tileWidth) / tileWidth; - y = this.game.math.snapToFloor(y, tileHeight) / tileHeight; - - if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height) - { - this.layers[layer].data[y][x] = index; - } - - this.dirty = true; - - }, - - // Values are in TILEs, not pixels. - copy: function (x, y, width, height, layer) { - - if (typeof layer === "undefined") { layer = this.currentLayer; } - - if (!this.layers[layer]) - { - this._results.length = 0; - return; - } - - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof width === "undefined") { width = this.layers[layer].width; } - if (typeof height === "undefined") { height = this.layers[layer].height; } - - if (x < 0) - { - x = 0; - } - - if (y < 0) - { - y = 0; - } - - if (width > this.layers[layer].width) - { - width = this.layers[layer].width; - } - - if (height > this.layers[layer].height) - { - height = this.layers[layer].height; - } - - this._results.length = 0; - - this._results.push( { x: x, y: y, width: width, height: height, layer: layer }); - - for (var ty = y; ty < y + height; ty++) - { - for (var tx = x; tx < x + width; tx++) - { - this._results.push({ x: tx, y: ty, index: this.layers[layer].data[ty][tx] }); - } - } - - return this._results; - - }, - - paste: function (x, y, tileblock, layer) { - - if (typeof x === "undefined") { x = 0; } - if (typeof y === "undefined") { y = 0; } - if (typeof layer === "undefined") { layer = this.currentLayer; } - - if (!tileblock || tileblock.length < 2) - { - return; - } - - // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste - var diffX = tileblock[1].x - x; - var diffY = tileblock[1].y - y; - - for (var i = 1; i < tileblock.length; i++) - { - this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ] = tileblock[i].index; - } - - this.dirty = true; - - }, - - /** - * Swap tiles with 2 kinds of indexes. - * @method swapTile - * @param {number} tileA - First tile index. - * @param {number} tileB - Second tile index. - * @param {number} [x] - specify a Rectangle of tiles to operate. The x position in tiles of Rectangle's left-top corner. - * @param {number} [y] - specify a Rectangle of tiles to operate. The y position in tiles of Rectangle's left-top corner. - * @param {number} [width] - specify a Rectangle of tiles to operate. The width in tiles. - * @param {number} [height] - specify a Rectangle of tiles to operate. The height in tiles. - */ - swap: function (tileA, tileB, x, y, width, height, layer) { - - this.copy(x, y, width, height, layer); - - if (this._results.length < 2) - { - return; - } - - this._tempA = tileA; - this._tempB = tileB; - - this._results.forEach(this.swapHandler, this); - - this.paste(x, y, this._results); - - }, - - swapHandler: function (value, index, array) { - - if (value.index === this._tempA) - { - this._results[index].index = this._tempB; - } - else if (value.index === this._tempB) - { - this._results[index].index = this._tempA; - } - - }, - - /** - * Swap tiles with 2 kinds of indexes. - * @method swapTile - * @param {number} tileA - First tile index. - * @param {number} tileB - Second tile index. - * @param {number} [x] - specify a Rectangle of tiles to operate. The x position in tiles of Rectangle's left-top corner. - * @param {number} [y] - specify a Rectangle of tiles to operate. The y position in tiles of Rectangle's left-top corner. - * @param {number} [width] - specify a Rectangle of tiles to operate. The width in tiles. - * @param {number} [height] - specify a Rectangle of tiles to operate. The height in tiles. - */ - forEach: function (callback, context, x, y, width, height, layer) { - - this.copy(x, y, width, height, layer); - - if (this._results.length < 2) - { - return; - } - - this._results.forEach(callback, context); - - this.paste(x, y, this._results); - - }, - - /** - * Replaces one type of tile with another. - * @method replace - * @param {number} tileA - First tile index. - * @param {number} tileB - Second tile index. - * @param {number} [x] - specify a Rectangle of tiles to operate. The x position in tiles of Rectangle's left-top corner. - * @param {number} [y] - specify a Rectangle of tiles to operate. The y position in tiles of Rectangle's left-top corner. - * @param {number} [width] - specify a Rectangle of tiles to operate. The width in tiles. - * @param {number} [height] - specify a Rectangle of tiles to operate. The height in tiles. - */ - replace: function (tileA, tileB, x, y, width, height, layer) { - - this.copy(x, y, width, height, layer); - - if (this._results.length < 2) - { - return; - } - - for (var i = 1; i < this._results.length; i++) - { - if (this._results[i].index === tileA) - { - this._results[i].index = tileB; - } - } - - this.paste(x, y, this._results); - - }, - - /** - * Randomises a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! - * @method random - * @param {number} tileA - First tile index. - * @param {number} tileB - Second tile index. - * @param {number} [x] - specify a Rectangle of tiles to operate. The x position in tiles of Rectangle's left-top corner. - * @param {number} [y] - specify a Rectangle of tiles to operate. The y position in tiles of Rectangle's left-top corner. - * @param {number} [width] - specify a Rectangle of tiles to operate. The width in tiles. - * @param {number} [height] - specify a Rectangle of tiles to operate. The height in tiles. - */ - random: function (x, y, width, height, layer) { - - if (typeof layer === "undefined") { layer = this.currentLayer; } - - this.copy(x, y, width, height, layer); - - if (this._results.length < 2) - { - return; - } - - var indexes = []; - - for (var t = 1; t < this._results.length; t++) - { - var idx = this._results[t].index; - - if (indexes.indexOf(idx) === -1) - { - indexes.push(idx); - } - } - - for (var i = 1; i < this._results.length; i++) - { - this._results[i].index = this.game.rnd.pick(indexes); - } - - this.paste(x, y, this._results); - - }, - - /** - * Randomises a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed! - * @method random - * @param {number} tileA - First tile index. - * @param {number} tileB - Second tile index. - * @param {number} [x] - specify a Rectangle of tiles to operate. The x position in tiles of Rectangle's left-top corner. - * @param {number} [y] - specify a Rectangle of tiles to operate. The y position in tiles of Rectangle's left-top corner. - * @param {number} [width] - specify a Rectangle of tiles to operate. The width in tiles. - * @param {number} [height] - specify a Rectangle of tiles to operate. The height in tiles. - */ - shuffle: function (x, y, width, height, layer) { - - if (typeof layer === "undefined") { layer = this.currentLayer; } - - this.copy(x, y, width, height, layer); - - if (this._results.length < 2) - { - return; - } - - var header = this._results.shift(); - - Phaser.Utils.shuffle(this._results); - - this._results.unshift(header); - - this.paste(x, y, this._results); - - }, - - /** - * Fill a tile block with a specific tile index. - * @method fill - * @param {number} index - Index of tiles you want to fill with. - * @param {number} [x] - X position (in tiles) of block's left-top corner. - * @param {number} [y] - Y position (in tiles) of block's left-top corner. - * @param {number} [width] - width of block. - * @param {number} [height] - height of block. - */ - fill: function (index, x, y, width, height, layer) { - - this.copy(x, y, width, height, layer); - - if (this._results.length < 2) - { - return; - } - - for (var i = 1; i < this._results.length; i++) - { - this._results[i].index = index; - } - - this.paste(x, y, this._results); - - }, - - removeAllLayers: function () { - - this.layers.length = 0; - this.currentLayer = 0; - - }, - - dump: function () { - - var txt = ''; - var args = ['']; - - for (var y = 0; y < this.layers[this.currentLayer].height; y++) - { - for (var x = 0; x < this.layers[this.currentLayer].width; x++) - { - txt += "%c "; - - if (this.layers[this.currentLayer].data[y][x] > 1) - { - if (this.debugMap[this.layers[this.currentLayer].data[y][x]]) - { - args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]); - } - else - { - args.push("background: #ffffff"); - } - } - else - { - args.push("background: rgb(0, 0, 0)"); - } - } - - txt += "\n"; - } - - args[0] = txt; - console.log.apply(console, args); - - }, - - destroy: function () { - - this.removeAllLayers(); - this.game = null; - - } - -}; - -// Maybe should extend Sprite? -Phaser.TilemapLayer = function (game, x, y, renderWidth, renderHeight, tileset, tilemap, layer) { - - /** - * @property {Phaser.Game} game - Description. - */ - this.game = game; - - /** - * @property {Description} canvas - Description. - * @default - */ - this.canvas = Phaser.Canvas.create(renderWidth, renderHeight); - - /** - * @property {Description} context - Description. - * @default - */ - this.context = this.canvas.getContext('2d'); - - /** - * @property {Description} baseTexture - Description. - * @default - */ - this.baseTexture = new PIXI.BaseTexture(this.canvas); - - /** - * @property {Description} texture - Description. - * @default - */ - this.texture = new PIXI.Texture(this.baseTexture); - - this.textureFrame = new Phaser.Frame(0, 0, 0, renderWidth, renderHeight, 'tilemaplayer', game.rnd.uuid()); - - Phaser.Sprite.call(this, this.game, x, y, this.texture, this.textureFrame); - - this.type = Phaser.TILEMAPLAYER; - - this.fixedToCamera = true; - - /** - * @property {Description} tileset - Description. - */ - this.tileset = null; - - this.tileWidth = 0; - this.tileHeight = 0; - this.tileMargin = 0; - this.tileSpacing = 0; - - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @property {number} widthInPixels - * @default - */ - this.widthInPixels = 0; - - /** - * Read-only variable, do NOT recommend changing after the map is loaded! - * @property {number} heightInPixels - * @default - */ - this.heightInPixels = 0; - - - this.renderWidth = renderWidth; - this.renderHeight = renderHeight; - - /** - * @property {number} _ga - Local render loop var to help avoid gc spikes. - * @private - */ - this._ga = 1; - - /** - * @property {number} _dx - Local render loop var to help avoid gc spikes. - * @private - */ - this._dx = 0; - - /** - * @property {number} _dy - Local render loop var to help avoid gc spikes. - * @private - */ - this._dy = 0; - - /** - * @property {number} _dw - Local render loop var to help avoid gc spikes. - * @private - */ - this._dw = 0; - - /** - * @property {number} _dh - Local render loop var to help avoid gc spikes. - * @private - */ - this._dh = 0; - - /** - * @property {number} _tx - Local render loop var to help avoid gc spikes. - * @private - */ - this._tx = 0; - - /** - * @property {number} _ty - Local render loop var to help avoid gc spikes. - * @private - */ - this._ty = 0; - - this._results = []; - - this._tw = 0; - this._th = 0; - - /** - * @property {number} _tl - Local render loop var to help avoid gc spikes. - * @private - */ - this._tl = 0; - - /** - * @property {number} _maxX - Local render loop var to help avoid gc spikes. - * @private - */ - this._maxX = 0; - - /** - * @property {number} _maxY - Local render loop var to help avoid gc spikes. - * @private - */ - this._maxY = 0; - - /** - * @property {number} _startX - Local render loop var to help avoid gc spikes. - * @private - */ - this._startX = 0; - - /** - * @property {number} _startY - Local render loop var to help avoid gc spikes. - * @private - */ - this._startY = 0; - - /** - * @property {number} scrollFactorX - speed at which this layer scrolls - * horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls - * half as quickly as the 'normal' camera-locked layers do) - * @default 1 - */ - this.scrollFactorX = 1; - /** - * @property {number} scrollFactorY - speed at which this layer scrolls - * vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls - * half as quickly as the 'normal' camera-locked layers do) - * @default 1 - */ - this.scrollFactorY = 1; - - this.tilemap = null; - this.layer = null; - this.index = 0; - - this._x = 0; - this._y = 0; - this._prevX = 0; - this._prevY = 0; - - this.dirty = true; - - if (tileset instanceof Phaser.Tileset || typeof tileset === 'string') - { - this.updateTileset(tileset); - } - - if (tilemap instanceof Phaser.Tilemap) - { - this.updateMapData(tilemap, layer); - } - -}; - -Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype); -Phaser.TilemapLayer.prototype = Phaser.Utils.extend(true, Phaser.TilemapLayer.prototype, Phaser.Sprite.prototype, PIXI.Sprite.prototype); -Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer; - - -Phaser.TilemapLayer.prototype.update = function () { - - this.scrollX = this.game.camera.x * this.scrollFactorX; - this.scrollY = this.game.camera.y * this.scrollFactorY; - - this.render(); - -} - -Phaser.TilemapLayer.prototype.resizeWorld = function () { - - this.game.world.setBounds(0, 0, this.widthInPixels, this.heightInPixels); - -} - -Phaser.TilemapLayer.prototype.updateTileset = function (tileset) { - - if (tileset instanceof Phaser.Tileset) - { - this.tileset = tileset; - } - else if (typeof tileset === 'string') - { - this.tileset = this.game.cache.getTileset('tiles'); - } - else - { - return; - } - - this.tileWidth = this.tileset.tileWidth; - this.tileHeight = this.tileset.tileHeight; - this.tileMargin = this.tileset.tileMargin; - this.tileSpacing = this.tileset.tileSpacing; - - this.updateMax(); - -} - -Phaser.TilemapLayer.prototype.updateMapData = function (tilemap, layer) { - - if (typeof layer === 'undefined') - { - layer = 0; - } - - if (tilemap instanceof Phaser.Tilemap) - { - this.tilemap = tilemap; - this.layer = this.tilemap.layers[layer]; - this.index = layer; - this.updateMax(); - this.tilemap.dirty = true; - } - -} - -/** - * Take an x coordinate that doesn't account for scrollFactorY and 'fix' it - * into a scrolled local space. Used primarily internally - * @param {number} x - x coordinate in camera space - * @return {number} x coordinate in scrollFactor-adjusted dimensions - */ -Phaser.TilemapLayer.prototype._fixX = function(x) { - - if (this.scrollFactorX === 1) - { - return x; - } - - var left_edge = x - (this._x / this.scrollFactorX); - - return this._x + left_edge; - -} - -/** - * Take an x coordinate that _does_ account for scrollFactorY and 'unfix' it - * back to camera space. Used primarily internally - * @param {number} x - x coordinate in scrollFactor-adjusted dimensions - * @return {number} x coordinate in camera space - */ -Phaser.TilemapLayer.prototype._unfixX = function(x) { - - if (this.scrollFactorX === 1) - { - return x; - } - - var left_edge = x - this._x; - - return (this._x / this.scrollFactorX) + left_edge; - -} - -/** - * Take a y coordinate that doesn't account for scrollFactorY and 'fix' it - * into a scrolled local space. Used primarily internally - * @param {number} y - y coordinate in camera space - * @return {number} y coordinate in scrollFactor-adjusted dimensions - */ -Phaser.TilemapLayer.prototype._fixY = function(y) { - - if (this.scrollFactorY === 1) - { - return y; - } - - var top_edge = y - (this._y / this.scrollFactorY); - - return this._y + top_edge; - -} - -/** - * Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it - * back to camera space. Used primarily internally - * @param {number} y - y coordinate in scrollFactor-adjusted dimensions - * @return {number} y coordinate in camera space - */ -Phaser.TilemapLayer.prototype._unfixY = function(y) { - - if (this.scrollFactorY === 1) - { - return y; - } - - var top_edge = y - this._y; - - return (this._y / this.scrollFactorY) + top_edge; - -} - -/** -* Convert a pixel value to a tile coordinate. -* @param {number} x - X position of the point in target tile. -* @param {number} [layer] - layer of this tile located. -* @return {number} The tile with specific properties. -*/ -Phaser.TilemapLayer.prototype.getTileX = function (x) { - - var tileWidth = this.tileWidth * this.scale.x; - - return this.game.math.snapToFloor(this._fixX(x), tileWidth) / tileWidth; - -} - -/** -* Convert a pixel value to a tile coordinate. -* @param {number} x - X position of the point in target tile. -* @param {number} [layer] - layer of this tile located. -* @return {number} The tile with specific properties. -*/ -Phaser.TilemapLayer.prototype.getTileY = function (y) { - - var tileHeight = this.tileHeight * this.scale.y; - - return this.game.math.snapToFloor(this._fixY(y), tileHeight) / tileHeight; - -} - -Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) { - - point.x = this.getTileX(x); - point.y = this.getTileY(y); - - return point; - -} - -/** -* -* @method getTileOverlaps -* @param {GameObject} object - Tiles you want to get that overlaps this. -* @return {array} Array with tiles informations (each contains x, y, and the tile). -*/ -Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides) { - - if (this.tilemap === null) - { - return; - } - - // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all) - if (typeof collides === 'undefined') { collides = false; } - - // Cap the values - - if (x < 0) - { - x = 0; - } - - if (y < 0) - { - y = 0; - } - - // adjust the x,y coordinates for scrollFactor - x = this._fixX( x ); - y = this._fixY( y ); - - if (width > this.widthInPixels) - { - width = this.widthInPixels; - } - - if (height > this.heightInPixels) - { - height = this.heightInPixels; - } - - var tileWidth = this.tileWidth * this.scale.x; - var tileHeight = this.tileHeight * this.scale.y; - - // Convert the pixel values into tile coordinates - this._tx = this.game.math.snapToFloor(x, tileWidth) / tileWidth; - this._ty = this.game.math.snapToFloor(y, tileHeight) / tileHeight; - this._tw = (this.game.math.snapToCeil(width, tileWidth) + tileWidth) / tileWidth; - this._th = (this.game.math.snapToCeil(height, tileHeight) + tileHeight) / tileHeight; - - // This should apply the layer x/y here - - // this._results.length = 0; - this._results = []; - - // pretty sure we don't use this any more? - // this._results.push( { x: x, y: y, width: width, height: height, tx: this._tx, ty: this._ty, tw: this._tw, th: this._th }); - - var _index = 0; - var _tile = null; - var sx = 0; - var sy = 0; - - for (var wy = this._ty; wy < this._ty + this._th; wy++) - { - for (var wx = this._tx; wx < this._tx + this._tw; wx++) - { - if (this.layer.data[wy] && this.layer.data[wy][wx]) - { - // Could combine - _index = this.layer.data[wy][wx] - 1; - _tile = this.tileset.getTile(_index); - - sx = _tile.width * this.scale.x; - sy = _tile.height * this.scale.y; - - if (collides == false || (collides && _tile.collideNone == false)) - { - // convert tile coordinates back to camera space for return - var _wx = this._unfixX( wx*sx ) / tileWidth; - var _wy = this._unfixY( wy*sy ) / tileHeight; - this._results.push({ x: _wx * sx, right: (_wx * sx) + sx, y: _wy * sy, bottom: (_wy * sy) + sy, width: sx, height: sy, tx: _wx, ty: _wy, tile: _tile }); - } - } - } - } - - return this._results; - -} - -Phaser.TilemapLayer.prototype.updateMax = function () { - - this._maxX = this.game.math.ceil(this.canvas.width / this.tileWidth) + 1; - this._maxY = this.game.math.ceil(this.canvas.height / this.tileHeight) + 1; - - if (this.layer) - { - if (this._maxX > this.layer.width) - { - this._maxX = this.layer.width; - } - - if (this._maxY > this.layer.height) - { - this._maxY = this.layer.height; - } - - this.widthInPixels = this.layer.width * this.tileWidth; - this.heightInPixels = this.layer.height * this.tileHeight; - } - - this.dirty = true; - -} - -Phaser.TilemapLayer.prototype.render = function () { - - if (this.tilemap && this.tilemap.dirty) - { - this.dirty = true; - } - - if (!this.dirty || !this.tileset || !this.tilemap || !this.visible) - { - return; - } - - this._prevX = this._dx; - this._prevY = this._dy; - - this._dx = -(this._x - (this._startX * this.tileWidth)); - this._dy = -(this._y - (this._startY * this.tileHeight)); - - this._tx = this._dx; - this._ty = this._dy; - - this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); - - for (var y = this._startY; y < this._startY + this._maxY; y++) - { - this._column = this.layer.data[y]; - - for (var x = this._startX; x < this._startX + this._maxX; x++) - { - // only -1 on TILED maps, not CSV - var tile = this.tileset.tiles[this._column[x]-1]; - - if (tile) - { - this.context.drawImage( - this.tileset.image, - tile.x, - tile.y, - this.tileWidth, - this.tileHeight, - Math.floor(this._tx), - Math.floor(this._ty), - this.tileWidth, - this.tileHeight - ); - } - - this._tx += this.tileWidth; - - } - - this._tx = this._dx; - this._ty += this.tileHeight; - } - - // Only needed if running in WebGL, otherwise this array will never get cleared down I don't think! - if (this.game.renderType == Phaser.WEBGL) - { - PIXI.texturesToUpdate.push(this.baseTexture); - } - - this.dirty = false; - - if (this.tilemap.dirty) - { - this.tilemap.dirty = false; - } - - return true; - -} - -Phaser.TilemapLayer.prototype.deltaAbsX = function () { - return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX()); -} - -Phaser.TilemapLayer.prototype.deltaAbsY = function () { - return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY()); -} - -Phaser.TilemapLayer.prototype.deltaX = function () { - return this._dx - this._prevX; -} - -Phaser.TilemapLayer.prototype.deltaY = function () { - return this._dy - this._prevY; -} - -Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", { - - get: function () { - return this._x; - }, - - set: function (value) { - - if (value !== this._x && value >= 0 && this.layer) - { - this._x = value; - - if (this._x > (this.widthInPixels - this.renderWidth)) - { - this._x = this.widthInPixels - this.renderWidth; - } - - this._startX = this.game.math.floor(this._x / this.tileWidth); - - if (this._startX < 0) - { - this._startX = 0; - } - - if (this._startX + this._maxX > this.layer.width) - { - this._startX = this.layer.width - this._maxX; - } - - this.dirty = true; - } - - } - -}); - -Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", { - - get: function () { - return this._y; - }, - - set: function (value) { - - if (value !== this._y && value >= 0 && this.layer) - { - this._y = value; - - if (this._y > (this.heightInPixels - this.renderHeight)) - { - this._y = this.heightInPixels - this.renderHeight; - } - - this._startY = this.game.math.floor(this._y / this.tileHeight); - - if (this._startY < 0) - { - this._startY = 0; - } - - if (this._startY + this._maxY > this.layer.height) - { - this._startY = this.layer.height - this._maxY; - } - - this.dirty = true; - } - - } - -}); - -Phaser.TilemapParser = { - - tileset: function (game, key, tileWidth, tileHeight, tileMax, tileMargin, tileSpacing) { - - // How big is our image? - var img = game.cache.getTilesetImage(key); - - if (img == null) - { - return null; - } - - var width = img.width; - var height = img.height; - - // If no tile width/height is given, try and figure it out (won't work if the tileset has margin/spacing) - if (tileWidth <= 0) - { - tileWidth = Math.floor(-width / Math.min(-1, tileWidth)); - } - - if (tileHeight <= 0) - { - tileHeight = Math.floor(-height / Math.min(-1, tileHeight)); - } - - var row = Math.round(width / tileWidth); - var column = Math.round(height / tileHeight); - var total = row * column; - - if (tileMax !== -1) - { - total = tileMax; - } - - // Zero or smaller than tile sizes? - if (width == 0 || height == 0 || width < tileWidth || height < tileHeight || total === 0) - { - console.warn("Phaser.TilemapParser.tileSet: width/height zero or width/height < given tileWidth/tileHeight"); - return null; - } - - // Let's create some tiles - var x = tileMargin; - var y = tileMargin; - - var tileset = new Phaser.Tileset(img, key, tileWidth, tileHeight, tileMargin, tileSpacing); - - for (var i = 0; i < total; i++) - { - tileset.addTile(new Phaser.Tile(tileset, i, x, y, tileWidth, tileHeight)); - - x += tileWidth + tileSpacing; - - if (x === width) - { - x = tileMargin; - y += tileHeight + tileSpacing; - } - } - - return tileset; - - }, - - parse: function (game, data, format) { - - if (format === Phaser.Tilemap.CSV) - { - return this.parseCSV(data); - } - else if (format === Phaser.Tilemap.TILED_JSON) - { - return this.parseTiledJSON(data); - } - - }, - - /** - * Parse csv map data and generate tiles. - * - * @method Phaser.Tilemap.prototype.parseCSV - * @param {string} data - CSV map data. - */ - parseCSV: function (data) { - - // Trim any rogue whitespace from the data - data = data.trim(); - - var output = []; - var rows = data.split("\n"); - var height = rows.length; - var width = 0; - - for (var i = 0; i < rows.length; i++) - { - output[i] = []; - - var column = rows[i].split(","); - - for (var c = 0; c < column.length; c++) - { - output[i][c] = parseInt(column[c]); - } - - if (width == 0) - { - width = column.length; - } - } - - return [{ name: 'csv', width: width, height: height, alpha: 1, visible: true, indexes: [], tileMargin: 0, tileSpacing: 0, data: output }]; - - }, - - /** - * Parse JSON map data and generate tiles. - * - * @method Phaser.Tilemap.prototype.parseTiledJSON - * @param {string} data - JSON map data. - * @param {string} key - Asset key for tileset image. - */ - parseTiledJSON: function (json) { - - var layers = []; - - for (var i = 0; i < json.layers.length; i++) - { - // Check it's a data layer - if (!json.layers[i].data) - { - continue; - } - - // json.tilewidth - // json.tileheight - - var layer = { - - name: json.layers[i].name, - width: json.layers[i].width, - height: json.layers[i].height, - alpha: json.layers[i].opacity, - visible: json.layers[i].visible, - indexes: [], - - tileMargin: json.tilesets[0].margin, - tileSpacing: json.tilesets[0].spacing, - - }; - - var output = []; - var c = 0; - var row; - - for (var t = 0; t < json.layers[i].data.length; t++) - { - if (c == 0) - { - row = []; - } - - row.push(json.layers[i].data[t]); - c++; - - if (c == json.layers[i].width) - { - output.push(row); - c = 0; - } - } - - layer.data = output; - - layers.push(layer); - - } - - return layers; - - } - -} - - -Phaser.Tileset = function (image, key, tileWidth, tileHeight, tileMargin, tileSpacing) { - - if (typeof tileMargin === "undefined") { tileMargin = 0; } - if (typeof tileSpacing === "undefined") { tileSpacing = 0; } - - /** - * @property {string} key - The cache ID. - */ - this.key = key; - - this.image = image; - - this.tileWidth = tileWidth; - this.tileHeight = tileHeight; - this.margin = tileMargin; - this.spacing = tileSpacing; - - this.tiles = []; - -} - -Phaser.Tileset.prototype = { - - addTile: function (tile) { - - this.tiles.push(tile); - - return tile; - - }, - - getTile: function (index) { - - if (this.tiles[index]) - { - return this.tiles[index]; - } - - return null; - - }, - - setSpacing: function (margin, spacing) { - - this.tileMargin = margin; - this.tileSpacing = spacing; - - }, - - canCollide: function (index) { - - if (this.tiles[index]) - { - return this.tiles[index].collideNone; - } - - return null; - - }, - - checkTileIndex: function (index) { - - return (this.tiles[index]); - - }, - - setCollisionRange: function (start, stop, left, right, up, down) { - - if (this.tiles[start] && this.tiles[stop] && start < stop) - { - for (var i = start; i <= stop; i++) - { - this.tiles[i].setCollision(left, right, up, down); - } - } - - }, - - setCollision: function (index, left, right, up, down) { - - if (this.tiles[index]) - { - this.tiles[index].setCollision(left, right, up, down); - } - - }, - -} - -/** -* @name Phaser.Tileset#total -* @property {number} total - The total number of tiles in this Tileset. -* @readonly -*/ -Object.defineProperty(Phaser.Tileset.prototype, "total", { - - get: function () { - return this.tiles.length; - } - -}); - -/** -* We're replacing a couple of Pixi's methods here to fix or add some vital functionality: -* -* 1) Added support for Trimmed sprite sheets -* 2) Skip display objects with an alpha of zero -* 3) Avoid Style Recalculation from the incorrect bgcolor value -* -* Hopefully we can remove this once Pixi has been updated to support these things. -*/ - -/** - * Renders the stage to its canvas view - * - * @method render - * @param stage {Stage} the Stage element to be rendered - */ -PIXI.CanvasRenderer.prototype.render = function(stage) -{ - PIXI.texturesToUpdate.length = 0; - PIXI.texturesToDestroy.length = 0; - - PIXI.visibleCount++; - stage.updateTransform(); - - // update the background color - // if(this.view.style.backgroundColor!=stage.backgroundColorString && !this.transparent)this.view.style.backgroundColor = stage.backgroundColorString; - - this.context.setTransform(1, 0, 0, 1, 0, 0); - this.context.clearRect(0, 0, this.width, this.height) - this.renderDisplayObject(stage); - - // Remove frame updates - if (PIXI.Texture.frameUpdates.length > 0) - { - PIXI.Texture.frameUpdates.length = 0; - } - -} - -PIXI.CanvasRenderer.prototype.renderDisplayObject = function(displayObject) -{ - // Once the display object hits this we can break the loop - var testObject = displayObject.last._iNext; - displayObject = displayObject.first; - - do - { - //transform = displayObject.worldTransform; - - if (!displayObject.visible) - { - displayObject = displayObject.last._iNext; - continue; - } - - if (!displayObject.renderable || displayObject.alpha == 0) - { - displayObject = displayObject._iNext; - continue; - } - - if (displayObject instanceof PIXI.Sprite) - { - // var frame = displayObject.texture.frame; - - if (displayObject.texture.frame) - { - this.context.globalAlpha = displayObject.worldAlpha; - - if (displayObject.texture.trimmed) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2] + displayObject.texture.trim.x, displayObject.worldTransform[5] + displayObject.texture.trim.y); - } - else - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]); - } - - this.context.drawImage( - displayObject.texture.baseTexture.source, - displayObject.texture.frame.x, - displayObject.texture.frame.y, - displayObject.texture.frame.width, - displayObject.texture.frame.height, - (displayObject.anchor.x) * -displayObject.texture.frame.width, - (displayObject.anchor.y) * -displayObject.texture.frame.height, - displayObject.texture.frame.width, - displayObject.texture.frame.height); - } - } - else if (displayObject instanceof PIXI.Strip) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) - this.renderStrip(displayObject); - } - else if (displayObject instanceof PIXI.TilingSprite) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) - this.renderTilingSprite(displayObject); - } - else if (displayObject instanceof PIXI.CustomRenderable) - { - displayObject.renderCanvas(this); - } - else if (displayObject instanceof PIXI.Graphics) - { - this.context.setTransform(displayObject.worldTransform[0], displayObject.worldTransform[3], displayObject.worldTransform[1], displayObject.worldTransform[4], displayObject.worldTransform[2], displayObject.worldTransform[5]) - PIXI.CanvasGraphics.renderGraphics(displayObject, this.context); - } - else if (displayObject instanceof PIXI.FilterBlock) - { - if (displayObject.open) - { - this.context.save(); - - var cacheAlpha = displayObject.mask.alpha; - var maskTransform = displayObject.mask.worldTransform; - - this.context.setTransform(maskTransform[0], maskTransform[3], maskTransform[1], maskTransform[4], maskTransform[2], maskTransform[5]) - - displayObject.mask.worldAlpha = 0.5; - - this.context.worldAlpha = 0; - - PIXI.CanvasGraphics.renderGraphicsMask(displayObject.mask, this.context); - this.context.clip(); - - displayObject.mask.worldAlpha = cacheAlpha; - } - else - { - this.context.restore(); - } - } - // count++ - displayObject = displayObject._iNext; - } - while(displayObject != testObject) - -} - -PIXI.WebGLBatch.prototype.update = function() -{ - var gl = this.gl; - var worldTransform, width, height, aX, aY, w0, w1, h0, h1, index, index2, index3 - - var a, b, c, d, tx, ty; - - var indexRun = 0; - - var displayObject = this.head; - - while(displayObject) - { - if(displayObject.vcount === PIXI.visibleCount) - { - width = displayObject.texture.frame.width; - height = displayObject.texture.frame.height; - - // TODO trim?? - aX = displayObject.anchor.x;// - displayObject.texture.trim.x - aY = displayObject.anchor.y; //- displayObject.texture.trim.y - w0 = width * (1-aX); - w1 = width * -aX; - - h0 = height * (1-aY); - h1 = height * -aY; - - index = indexRun * 8; - - worldTransform = displayObject.worldTransform; - - a = worldTransform[0]; - b = worldTransform[3]; - c = worldTransform[1]; - d = worldTransform[4]; - tx = worldTransform[2]; - ty = worldTransform[5]; - - if (displayObject.texture.trimmed) - { - tx += displayObject.texture.trim.x; - ty += displayObject.texture.trim.y; - } - - this.verticies[index + 0 ] = a * w1 + c * h1 + tx; - this.verticies[index + 1 ] = d * h1 + b * w1 + ty; - - this.verticies[index + 2 ] = a * w0 + c * h1 + tx; - this.verticies[index + 3 ] = d * h1 + b * w0 + ty; - - this.verticies[index + 4 ] = a * w0 + c * h0 + tx; - this.verticies[index + 5 ] = d * h0 + b * w0 + ty; - - this.verticies[index + 6] = a * w1 + c * h0 + tx; - this.verticies[index + 7] = d * h0 + b * w1 + ty; - - if(displayObject.updateFrame || displayObject.texture.updateFrame) - { - this.dirtyUVS = true; - - var texture = displayObject.texture; - - var frame = texture.frame; - var tw = texture.baseTexture.width; - var th = texture.baseTexture.height; - - this.uvs[index + 0] = frame.x / tw; - this.uvs[index +1] = frame.y / th; - - this.uvs[index +2] = (frame.x + frame.width) / tw; - this.uvs[index +3] = frame.y / th; - - this.uvs[index +4] = (frame.x + frame.width) / tw; - this.uvs[index +5] = (frame.y + frame.height) / th; - - this.uvs[index +6] = frame.x / tw; - this.uvs[index +7] = (frame.y + frame.height) / th; - - displayObject.updateFrame = false; - } - - // TODO this probably could do with some optimisation.... - if(displayObject.cacheAlpha != displayObject.worldAlpha) - { - displayObject.cacheAlpha = displayObject.worldAlpha; - - var colorIndex = indexRun * 4; - this.colors[colorIndex] = this.colors[colorIndex + 1] = this.colors[colorIndex + 2] = this.colors[colorIndex + 3] = displayObject.worldAlpha; - this.dirtyColors = true; - } - } - else - { - index = indexRun * 8; - - this.verticies[index + 0 ] = 0; - this.verticies[index + 1 ] = 0; - - this.verticies[index + 2 ] = 0; - this.verticies[index + 3 ] = 0; - - this.verticies[index + 4 ] = 0; - this.verticies[index + 5 ] = 0; - - this.verticies[index + 6] = 0; - this.verticies[index + 7] = 0; - } - - indexRun++; - displayObject = displayObject.__next; - } -} - return Phaser; -}); \ No newline at end of file diff --git a/examples/wip/bounds.js b/examples/wip/bounds.js deleted file mode 100644 index 5457358e1..000000000 --- a/examples/wip/bounds.js +++ /dev/null @@ -1,32 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', 'assets/sprites/exocet_spaceman.png'); - -} - -var sprite; - -function create() { - - game.stage.backgroundColor = '#997683'; - - sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'pic'); - sprite.anchor.setTo(0.5); - -} - - -function update() { - - sprite.rotation += 0.01; - -} - -function render() { - - game.debug.geom(sprite.getLocalBounds(), 'rgb(255, 255, 255)', false); - -} diff --git a/examples/wip/camera follow.js b/examples/wip/camera follow.js deleted file mode 100644 index 74e4f8a28..000000000 --- a/examples/wip/camera follow.js +++ /dev/null @@ -1,52 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var cursors; -var sprite; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.image(0, 0, 'backdrop'); - - sprite = game.add.sprite(300, 300, 'box'); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - sprite.x -= 8; - } - else if (cursors.right.isDown) - { - sprite.x += 8; - } - - if (cursors.up.isDown) - { - sprite.y -= 8; - } - else if (cursors.down.isDown) - { - sprite.y += 8; - } - -} - -function render() { - - -} diff --git a/examples/wip/camera.js b/examples/wip/camera.js deleted file mode 100644 index 081abc74b..000000000 --- a/examples/wip/camera.js +++ /dev/null @@ -1,47 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var cursors; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.sprite(0, 0, 'backdrop'); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 8; - } - else if (cursors.right.isDown) - { - game.camera.x += 8; - } - - if (cursors.up.isDown) - { - game.camera.y -= 8; - } - else if (cursors.down.isDown) - { - game.camera.y += 8; - } - -} - -function render() { - - -} diff --git a/examples/wip/cannon.js b/examples/wip/cannon.js deleted file mode 100644 index 31b11b00e..000000000 --- a/examples/wip/cannon.js +++ /dev/null @@ -1,136 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('arrow', 'assets/sprites/arrow.png'); - game.load.image('arrow', 'assets/sprites/thrust_ship2.png'); - game.load.image('chunk', 'assets/sprites/chunk.png'); - game.load.image('box', 'assets/sprites/block.png'); - game.load.spritesheet('bullets', 'assets/sprites/balls.png', 17, 17); - -} - -var cannon; -var bullets; -var angle = 0; -var fireRate = 100; -var nextFire = 0; -var cursors; -var boxes; -var playerGroup; -var bulletGroup; -var boxGroup; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - game.physics.gravity[1] = -8.5; - game.physics.defaultRestitution = 0.8; - game.physics.defaultFriction = 0.1; - - bullets = game.add.group(); - bullets.createMultiple(250, 'bullets', 0, false); - - cannon = game.add.sprite(50, 500, 'arrow'); - cannon.name = 'ship'; - cannon.physicsEnabled = true; - cannon.body.setCircle(32); - - playerGroup = game.physics.createCollisionGroup(); - bulletGroup = game.physics.createCollisionGroup(); - boxGroup = game.physics.createCollisionGroup(); - - cannon.body.setCollisionGroup(playerGroup); - cannon.body.collides(boxGroup); - - boxes = game.add.group(); - - for (var i = 0; i < 30; i++) - { - var box = boxes.create(game.rnd.integerInRange(100, 700), game.rnd.integerInRange(100, 500), 'box'); - box.name = 'box' + i; - box.scale.set(game.rnd.realInRange(0.2, 0.7)); - box.physicsEnabled = true; - box.body.setCollisionGroup(boxGroup); - box.body.collides( [ playerGroup, bulletGroup, boxGroup ]); - } - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function fire() { - - if (game.time.now > nextFire) - { - nextFire = game.time.now + fireRate; - - var bullet = bullets.getFirstExists(false); - - if (bullet) - { - bullet.frame = game.rnd.integerInRange(0,6); - bullet.exists = true; - bullet.position.set(cannon.x, cannon.y); - bullet.physicsEnabled = true; - bullet.body.collideWorldBounds = false; - bullet.body.rotation = cannon.rotation - game.math.degToRad(90); - - var magnitude = game.math.px2p(-500); - var angle = bullet.body.rotation + Math.PI / 2; - - bullet.body.velocity.x = magnitude * Math.cos(angle); - bullet.body.velocity.y = magnitude * Math.sin(angle); - - bullet.body.setCollisionGroup(bulletGroup); - bullet.body.collides(boxGroup); - } - } - -} - -function update() { - - if (cursors.left.isDown) - { - cannon.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - cannon.body.rotateRight(100); - } - else - { - cannon.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - // cannon.body.moveForward(200); - cannon.body.thrust(200); - } - else if (cursors.down.isDown) - { - // cannon.body.moveBackward(200); - cannon.body.reverse(200); - } - - var dx = game.input.activePointer.worldX - cannon.x; - var dy = game.input.activePointer.worldY - cannon.y; - cannon.rotation = Math.atan2(dy, dx); - - if (game.input.activePointer.isDown) - { - fire(); - } - -} - -function render() { - - game.debug.physicsBody(cannon.body); - -} diff --git a/examples/wip/class update.js b/examples/wip/class update.js deleted file mode 100644 index 869ea14b3..000000000 --- a/examples/wip/class update.js +++ /dev/null @@ -1,38 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -ClassA = function(game, x, y, texture) { - Phaser.Sprite.call(this, game, x, y, texture); -} - -ClassA.prototype = Object.create(Phaser.Sprite.prototype); -ClassA.prototype.constructor = ClassA; - -ClassA.prototype.update = function() { - console.log("here"); -} - -function preload() { - - game.load.image('pic', 'assets/pics/questar.png'); - -} - -var sprite; - -function create() { - - sprite = new ClassA(game, 100, 100, 'pic'); - - game.add.existing(sprite); - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/cocoon.php b/examples/wip/cocoon.php deleted file mode 100644 index 1fa8c73ee..000000000 --- a/examples/wip/cocoon.php +++ /dev/null @@ -1,24 +0,0 @@ - - - - - phaser - - - - - - - -
- - - \ No newline at end of file diff --git a/examples/wip/contact1.js b/examples/wip/contact1.js deleted file mode 100644 index 0f372940b..000000000 --- a/examples/wip/contact1.js +++ /dev/null @@ -1,135 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('dude', 'assets/games/starstruck/dude.png', 32, 48); - game.load.image('background', 'assets/games/starstruck/background2.png'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var player; -var facing = 'left'; -var jumpTimer = 0; -var cursors; -var jumpButton; -var boxes; - -function create() { - - game.stage.backgroundColor = '#000000'; - - bg = game.add.tileSprite(0, 0, 800, 600, 'background'); - bg.fixedToCamera = true; - - game.physics.gravity.y = 20; - - game.physics.friction = 0.5; - - player = game.add.sprite(50, 400, 'dude'); - player.physicsEnabled = true; - player.body.fixedRotation = true; - - player.animations.add('left', [0, 1, 2, 3], 10, true); - player.animations.add('turn', [4], 20, true); - player.animations.add('right', [5, 6, 7, 8], 10, true); - - boxes = game.add.group(); - - for (var i = 0; i < 1; i++) - { - // var box = boxes.create(game.rnd.integerInRange(200, 700), game.rnd.integerInRange(0, 100), 'box'); - var box = boxes.create(game.rnd.integerInRange(200, 700), 550, 'box'); - // box.scale.set(0.5); - // box.scale.set(game.rnd.realInRange(0.2, 0.7)); - box.physicsEnabled = true; - box.body.static = true; - box.body.fixedRotation = true; - box.body.createBodyCallback(player.body, gotBox, this); - } - - cursors = game.input.keyboard.createCursorKeys(); - jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); - -} - -function gotBox(body1, body2, shape1, shape2) { - - console.log('gotBox'); - - body1.sprite.kill(); - -} - -function update() { - - if (cursors.left.isDown) - { - player.body.moveLeft(200); - - if (facing != 'left') - { - player.animations.play('left'); - facing = 'left'; - } - } - else if (cursors.right.isDown) - { - player.body.moveRight(200); - - if (facing != 'right') - { - player.animations.play('right'); - facing = 'right'; - } - } - else - { - player.body.velocity.x = 0; - - if (facing != 'idle') - { - player.animations.stop(); - - if (facing == 'left') - { - player.frame = 0; - } - else - { - player.frame = 5; - } - - facing = 'idle'; - } - } - - if (jumpButton.isDown && game.time.now > jumpTimer && checkIfCanJump()) - { - player.body.moveUp(300); - jumpTimer = game.time.now + 750; - } - -} - -function checkIfCanJump(){ -var yAxis = p2.vec2.fromValues(0,1); -var result = false; -for(var i=0; i 0.5) result = true; - } -} -return result; -} - - -function render () { - - game.debug.physicsBody(player.body); - -} diff --git a/examples/wip/contact2.js b/examples/wip/contact2.js deleted file mode 100644 index 59cb03727..000000000 --- a/examples/wip/contact2.js +++ /dev/null @@ -1,143 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('dude', 'assets/games/starstruck/dude.png', 32, 48); - game.load.image('background', 'assets/games/starstruck/background2.png'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var player; -var facing = 'left'; -var jumpTimer = 0; -var cursors; -var jumpButton; -var boxes; - -function create() { - - game.stage.backgroundColor = '#000000'; - - bg = game.add.tileSprite(0, 0, 800, 600, 'background'); - bg.fixedToCamera = true; - - game.physics.gravity.y = 20; - game.physics.friction = 0.5; - // game.physics.setBoundsToWorld(); - - var playerCG = game.physics.createCollisionGroup(); - var boxCG = game.physics.createCollisionGroup(); - - player = game.add.sprite(50, 550, 'dude'); - player.name = 'player'; - player.physicsEnabled = true; - player.body.fixedRotation = true; - player.body.setCollisionGroup(playerCG); - - player.animations.add('left', [0, 1, 2, 3], 10, true); - player.animations.add('turn', [4], 20, true); - player.animations.add('right', [5, 6, 7, 8], 10, true); - - boxes = game.add.group(); - - for (var i = 0; i < 10; i++) - { - var box = boxes.create(200 + (i * 50), 550, 'box'); - box.name = 'box' + i; - box.scale.set(0.5); - box.physicsEnabled = true; - box.body.setCollisionGroup(boxCG); - box.body.collides(playerCG); - box.body.fixedRotation = true; - } - - // Because player is creating the collides callback, the parameter order will be: callback (playerBody, boxBody, playerShape, boxShape) - player.body.collides(boxCG, gotBox, this); - - - cursors = game.input.keyboard.createCursorKeys(); - jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); - -} - -function gotBox(body1, body2, shape1, shape2) { - - console.log('gotBox', body1.sprite.name, body2.sprite.name); - - body2.sprite.kill(); - -} - -function update() { - - if (cursors.left.isDown) - { - player.body.moveLeft(200); - - if (facing != 'left') - { - player.animations.play('left'); - facing = 'left'; - } - } - else if (cursors.right.isDown) - { - player.body.moveRight(200); - - if (facing != 'right') - { - player.animations.play('right'); - facing = 'right'; - } - } - else - { - player.body.velocity.x = 0; - - if (facing != 'idle') - { - player.animations.stop(); - - if (facing == 'left') - { - player.frame = 0; - } - else - { - player.frame = 5; - } - - facing = 'idle'; - } - } - - if (jumpButton.isDown && game.time.now > jumpTimer && checkIfCanJump()) - { - player.body.moveUp(300); - jumpTimer = game.time.now + 750; - } - -} - -function checkIfCanJump(){ -var yAxis = p2.vec2.fromValues(0,1); -var result = false; -for(var i=0; i 0.5) result = true; - } -} -return result; -} - - -function render () { - - game.debug.physicsBody(player.body); - -} diff --git a/examples/wip/crop.js b/examples/wip/crop.js deleted file mode 100644 index cf6f0794a..000000000 --- a/examples/wip/crop.js +++ /dev/null @@ -1,47 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var image; -var image2; -var r; - -function create() { - - image = game.add.image(32, 50, 'pic'); - image2 = game.add.image(32, 250, 'pic'); - - r = new Phaser.Rectangle(0, 0, 0, 176); - - image2.crop(r); - -} - -function update() { - - if (r !== null) - { - r.width += 1; - - image2.crop(r); - - if (r.width == 720) - { - image2.crop(); - r = null; - } - } - -} - -function render() { - - game.debug.text(image2.width, 32, 32); - -} diff --git a/examples/wip/debug.js b/examples/wip/debug.js deleted file mode 100644 index 47f88037a..000000000 --- a/examples/wip/debug.js +++ /dev/null @@ -1,35 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -var tilesprite; -var cursors; -var count = 0; - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var sprite; - -function create() { - - var tile = game.add.tileSprite(0, 0, 800, 600, 'starfield'); - tile.autoScroll(0, 200); - - sprite = game.add.image(200, 200, 'mummy'); - -} - -function update() { - -} - -function render() { - - game.debug.spriteInfo(sprite, 32, 32); - -} diff --git a/examples/wip/destroy state swap.js b/examples/wip/destroy state swap.js deleted file mode 100644 index a6e42d6df..000000000 --- a/examples/wip/destroy state swap.js +++ /dev/null @@ -1,36 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; -var anim; - -function create() { - - game.stage.backgroundColor = 0xff8855; - - mummy = game.add.sprite(300, 200, 'mummy', 5); - - mummy.animations.updateIfVisible = false; - - anim = mummy.animations.add('walk'); - - anim.play(2, false); - // anim.play(2, true); - -} - -function update() { - -} - -function render() { - - game.debug.text(anim.frame + ' / 17', 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/destroy state.js b/examples/wip/destroy state.js deleted file mode 100644 index 827338183..000000000 --- a/examples/wip/destroy state.js +++ /dev/null @@ -1,77 +0,0 @@ -var BasicGame = {}; - -BasicGame.Boot = function (game) { -}; - -BasicGame.Boot.prototype = { - - preload: function () { - - this.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - - }, - - create: function () { - - this.state.start('MainMenu'); - - } - -}; - -BasicGame.MainMenu = function (game) { - - this.mummy; - this.anim; - -}; - -BasicGame.MainMenu.prototype = { - - create: function () { - - this.stage.backgroundColor = 0x2d2d2d; - - this.mummy = this.add.sprite(200, 400, 'mummy'); - - this.anim = this.mummy.animations.add('walk'); - - this.anim.play(10, false); - - this.mummy.events.onAnimationComplete.add(this.changeIt, this); - - }, - - changeIt: function () { - - this.state.start('GameOver'); - - } - -}; - -BasicGame.GameOver = function (game) { - - this.dude; - -}; - -BasicGame.GameOver.prototype = { - - create: function () { - - this.stage.backgroundColor = 0xff7744; - - this.dude = this.add.sprite(300, 300, 'mummy'); - - } - -}; - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example'); - -game.state.add('Boot', BasicGame.Boot); -game.state.add('MainMenu', BasicGame.MainMenu); -game.state.add('GameOver', BasicGame.GameOver); - -game.state.start('Boot'); diff --git a/examples/wip/destroy.js b/examples/wip/destroy.js deleted file mode 100644 index 77857c313..000000000 --- a/examples/wip/destroy.js +++ /dev/null @@ -1,57 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }, false); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var sprite; -var sprite2; -var g; -var p; - -function create() { - - // game.stage.backgroundColor = '#ff5500'; - - // game.renderer.useFillRect = false; - - sprite = game.add.sprite(0.5, 0, 'pic'); - // sprite2 = game.add.sprite(0, 300, 'pic'); - - sprite.inputEnabled = true; - sprite.events.onInputDown.add(tint, this); - sprite.events.onInputUp.add(wibble, this); - - // game.add.tween(sprite).to({y: 500}, 3000, Phaser.Easing.Linear.None, true); - - // p = new PIXI.Point(43, 45); - -} - -function tint() { - - sprite.destroy(); - // sprite.tint = Math.random() * 0xFFFFFF; - // sprite2.tint = Math.random() * 0xFFFFFF; - -} - -function wibble() { - - console.log(sprite); - -} - -function update() { - - -} - -function render() { - - // game.debug.text(sprite.position.y, 32, 32); - -} diff --git a/examples/wip/filters/TRSIPlasmaFilter.js b/examples/wip/filters/TRSIPlasmaFilter.js deleted file mode 100644 index 1381cc493..000000000 --- a/examples/wip/filters/TRSIPlasmaFilter.js +++ /dev/null @@ -1,94 +0,0 @@ -PIXI.TRSIPlasmaFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates } - }; - - // Shader by Rebb / TRSI (https://www.shadertoy.com/view/XdX3Wn) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "// Rebb/TRSi^Paradise", - - "float an= sin(iGlobalTime)/3.14157;", - "float as= sin(an);", - "float zoo = .23232+.38*sin(.7*iGlobalTime);", - "void main(void)", - "{", - "vec2 position = ( gl_FragCoord.xy / iResolution.xy *3.3 );", - - "float color = 0.0;", - "color += sin(position.x - position.y) ;", - "color += sin(iGlobalTime)* cos(sin(iGlobalTime)*position.y*position.x*sin(position.x))+.008;", - "color += sin(iGlobalTime)+position.x*sin(position.y*sin(sin(tan(cos (iGlobalTime)))));", - "gl_FragColor = vec4( vec3(sin(color*color)*4.0, sin(color*color) , color )*sin(iGlobalTime+position.x/(iGlobalTime*3.14)),iGlobalTime/10.828 );", - - "}"]; - -} - -PIXI.TRSIPlasmaFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.TRSIPlasmaFilter.prototype.constructor = PIXI.TRSIPlasmaFilter; - -Object.defineProperty(PIXI.TRSIPlasmaFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.TRSIPlasmaFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/binarySerpentsFilter.js b/examples/wip/filters/binarySerpentsFilter.js deleted file mode 100644 index f8f656eb5..000000000 --- a/examples/wip/filters/binarySerpentsFilter.js +++ /dev/null @@ -1,130 +0,0 @@ -PIXI.BinarySerpentsFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by Trisomie21 (https://www.shadertoy.com/view/MslGRH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "// With tweaks by PauloFalcao", - - "float Texture3D(vec3 n, float res){", - "n = floor(n*res+.5);", - "return fract(sin((n.x+n.y*1e5+n.z*1e7)*1e-4)*1e5);", - "}", - - "float map( vec3 p ){", - "p.x+=sin(p.z*4.0+iGlobalTime*4.0)*0.1*cos(iGlobalTime*0.1);", - "p = mod(p,vec3(1.0, 1.0, 1.0))-0.5;", - "return length(p.xy)-.1;", - "}", - - "void main( void )", - "{", - "vec2 pos = (gl_FragCoord.xy*2.0 - iResolution.xy) / iResolution.y;", - "vec3 camPos = vec3(cos(iGlobalTime*0.3), sin(iGlobalTime*0.3), 1.5);", - "vec3 camTarget = vec3(0.0, 0.0, 0.0);", - - "vec3 camDir = normalize(camTarget-camPos);", - "vec3 camUp = normalize(vec3(0.0, 1.0, 0.0));", - "vec3 camSide = cross(camDir, camUp);", - "float focus = 2.0;", - - "vec3 rayDir = normalize(camSide*pos.x + camUp*pos.y + camDir*focus);", - "vec3 ray = camPos;", - "float d = 0.0, total_d = 0.0;", - "const int MAX_MARCH = 100;", - "const float MAX_DISTANCE = 5.0;", - "float c = 1.0;", - "for(int i=0; iMAX_DISTANCE) { c = 0.; total_d=MAX_DISTANCE; break; }", - "}", - - "float fog = 5.0;", - "vec4 result = vec4( vec3(c*.4 , c*.6, c) * (fog - total_d) / fog, 1.0 );", - - "ray.z -= 5.+iGlobalTime*.5;", - "float r = Texture3D(ray, 33.);", - "gl_FragColor = result*(step(r,.3)+r*.2+.1);", - "}"]; - - - -} - -PIXI.BinarySerpentsFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.BinarySerpentsFilter.prototype.constructor = PIXI.BinarySerpentsFilter; - -Object.defineProperty(PIXI.BinarySerpentsFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex01.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.BinarySerpentsFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/c64PlasmaFilter.js b/examples/wip/filters/c64PlasmaFilter.js deleted file mode 100644 index 48ceb0316..000000000 --- a/examples/wip/filters/c64PlasmaFilter.js +++ /dev/null @@ -1,136 +0,0 @@ -PIXI.C64PlasmaFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates } - }; - - // Shader by ssdsa (https://www.shadertoy.com/view/MslGzN) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "// 2D plasma in C64 graphics style", - "//", - "// Version 1.0 (2013-03-31)", - "// Simon Stelling-de San Antonio", - - "float camtime = 1.23*iGlobalTime;", - - "void main(void)", - "{", - "vec2 p = gl_FragCoord.xy / iResolution.xy;", - "p.y = 1.0 - p.y;", - "p *= 200.0;", - "p.x *= (iResolution.x / iResolution.y);", - "p.x /= 2.0;", - "p = floor(p);", - "p.x *= 2.0;", - "float a = p.x+30.0*sin(p.x/21.0 + 0.3*sin(0.4*camtime))+20.0*cos(p.y/19.0 + 0.2*cos(0.6*camtime))-160.0;", - "float b = p.y+30.0*cos(p.y/18.0 + 0.4*sin(0.7*camtime))+20.0*sin(p.x/16.0 + 0.5*cos(0.7*camtime))- 97.0;", - "float e = floor((length(vec2(a,b))", - "+4.0*mod(floor((p.x+p.y+p.y)/2.0),2.0))/13.0);", - "float c;", - "if (e == 0.0) { c = 9.0;", - "} else if (e == 1.0) { c = 2.0;", - "} else if (e == 2.0) { c = 8.0;", - "} else if (e == 3.0) { c = 10.0;", - "} else if (e == 4.0) { c = 15.0;", - "} else if (e == 5.0) { c = 7.0;", - "} else if (e == 6.0) { c = 1.0;", - "} else if (e == 7.0) { c = 13.0;", - "} else if (e == 8.0) { c = 3.0;", - "} else if (e == 9.0) { c = 14.0;", - "} else if (e == 10.0) { c = 4.0;", - "} else if (e == 11.0) { c = 6.0;", - "} else if (e == 12.0) { c = 0.0;", - "} else if (e == 13.0) { c = 11.0;", - "} else if (e == 14.0) { c = 5.0;", - "} else { c = 12.0;", - "}", - "vec3 col;", - "if (c == 0.0) { col = vec3(0.0);", - "} else if (c == 1.0) { col = vec3(1.0);", - "} else if (c == 2.0) { col = vec3(137.0, 64.0, 54.0)/256.0;", - "} else if (c == 3.0) { col = vec3(122.0, 191.0, 199.0)/256.0;", - "} else if (c == 4.0) { col = vec3(138.0, 70.0, 174.0)/256.0;", - "} else if (c == 5.0) { col = vec3(104.0, 169.0, 65.0)/256.0;", - "} else if (c == 6.0) { col = vec3( 62.0, 49.0, 162.0)/256.0;", - "} else if (c == 7.0) { col = vec3(208.0, 220.0, 113.0)/256.0;", - "} else if (c == 8.0) { col = vec3(144.0, 95.0, 37.0)/256.0;", - "} else if (c == 9.0) { col = vec3( 92.0, 71.0, 0.0)/256.0;", - "} else if (c == 10.0) { col = vec3(187.0, 119.0, 109.0)/256.0;", - "} else if (c == 11.0) { col = vec3( 85.0, 85.0, 85.0)/256.0;", - "} else if (c == 12.0) { col = vec3(128.0, 128.0, 128.0)/256.0;", - "} else if (c == 13.0) { col = vec3(172.0, 234.0, 136.0)/256.0;", - "} else if (c == 14.0) { col = vec3(124.0, 112.0, 218.0)/256.0;", - "} else { col = vec3(171.0, 171.0, 171.0)/256.0;", - "}", - "gl_FragColor = vec4(col,1.0);", - "}"]; - -} - -PIXI.C64PlasmaFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.C64PlasmaFilter.prototype.constructor = PIXI.C64PlasmaFilter; - -Object.defineProperty(PIXI.C64PlasmaFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.C64PlasmaFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/caustic lights.js b/examples/wip/filters/caustic lights.js deleted file mode 100644 index bc056836f..000000000 --- a/examples/wip/filters/caustic lights.js +++ /dev/null @@ -1,125 +0,0 @@ -PIXI.BinarySerpentsFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - -this.fragmentSrc = [ - "#ifdef GL_ES", - "precision mediump float;", - "#endif", - "//Ashok Gowtham M", - "//UnderWater Caustic lights", - "uniform float time;", - "uniform vec2 mouse;", - "uniform vec2 resolution;", - "//normalized sin", - "float sinn(float x)", - "{", - "return sin(x)/2.+.001;", - "}", - - "float CausticPatternFn(vec2 pos)", - "{", - "return (sin(pos.x*40.+time)", - "+pow(sin(-pos.x*130.+time),1.)", - "+pow(sin(pos.x*30.+time),2.)", - "+pow(sin(pos.x*50.+time),2.)", - "+pow(sin(pos.x*80.+time),2.)", - "+pow(sin(pos.x*90.+time),2.)", - "+pow(sin(pos.x*12.+time),2.)", - "+pow(sin(pos.x*6.+time),2.)", - "+pow(sin(-pos.x*13.+time),5.))/2.;", - "}", - - "vec2 CausticDistortDomainFn(vec2 pos)", - "{", - "pos.x*=(pos.y*0.60+1.);", - "pos.x*=1.+sin(time/2.)/10.;", - "return pos;", - "}", - - "void main( void )", - "{", - "vec2 pos = gl_FragCoord.xy/resolution;", - "pos-=.5;", - "vec2 CausticDistortedDomain = CausticDistortDomainFn(pos);", - "float CausticShape = clamp(7.-length(CausticDistortedDomain.x*20.),0.,1.);", - "float CausticPattern = CausticPatternFn(CausticDistortedDomain);", - "float CausticOnFloor = CausticPatternFn(pos)+sin(pos.y*100.)*clamp(2.-length(pos*2.),0.,1.);", - "float Caustic;", - "Caustic += CausticShape*CausticPattern;", - "Caustic *= (pos.y+.5)/4.;", - "//Caustic += CausticOnFloor;", - "float f = length(pos+vec2(-.5,.5))*length(pos+vec2(.5,.5))*(1.+Caustic)/1.;", - - - "gl_FragColor = vec4(.1,.5,.6,1)*(f);", - - "}"]; - - -} - -PIXI.BinarySerpentsFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.BinarySerpentsFilter.prototype.constructor = PIXI.BinarySerpentsFilter; - -Object.defineProperty(PIXI.BinarySerpentsFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex01.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.BinarySerpentsFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/checkerWaveFilter.js b/examples/wip/filters/checkerWaveFilter.js deleted file mode 100644 index b51469f28..000000000 --- a/examples/wip/filters/checkerWaveFilter.js +++ /dev/null @@ -1,154 +0,0 @@ -PIXI.CheckerWaveFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - resolution: { type: '2f', value: { x: width, y: height }}, - mouse: { type: '2f', value: { x: 0, y: 0 }}, - time: { type: '1f', value: 1 } - }; - - // http://glsl.heroku.com/e#12260.0 - - // Heroku shader conversion - - this.fragmentSrc = [ - "precision mediump float;", - - "#ifdef GL_ES", - "precision highp float;", - "#endif", - - "uniform vec2 resolution;", - "uniform float time;", - - "//Scene Start", - - "//Floor", - "vec2 obj0(in vec3 p){", - "//obj deformation", - "p.y=p.y+sin(sqrt(p.x*p.x+p.z*p.z)-time*4.0)*0.5;", - "//plane", - "return vec2(p.y+3.0,0);", - "}", - "//Floor Color (checkerboard)", - "vec3 obj0_c(in vec3 p){", - "if (fract(p.x*.5)>.5)", - "if (fract(p.z*.5)>.5)", - "return vec3(0,1,1);", - "else", - "return vec3(1,1,1);", - "else", - "if (fract(p.z*.5)>.5)", - "return vec3(1,1,1);", - "else", - "return vec3(0,1,1);", - "}", - - "//Scene End", - - "void main(void){", - "vec2 vPos=-1.0+2.0*gl_FragCoord.xy/resolution.xy;", - - "//Camera animation", - "vec3 vuv=vec3(0,2,sin(time*0.1));//Change camere up vector here", - "vec3 prp=vec3(-sin(time*0.6)*8.0,0,cos(time*0.4)*8.0); //Change camera path position here", - "vec3 vrp=vec3(0,-5,0); //Change camere view here", - - - "//Camera setup", - "vec3 vpn=normalize(vrp-prp);", - "vec3 u=normalize(cross(vuv,vpn));", - "vec3 v=cross(vpn,u);", - "vec3 vcv=(prp+vpn);", - "vec3 scrCoord=vcv+vPos.x*u*resolution.x/resolution.y+vPos.y*v;", - "vec3 scp=normalize(scrCoord-prp);", - - "//Raymarching", - "const vec3 e=vec3(0.1,0,0);", - "const float maxd=80.0; //Max depth", - - "vec2 s=vec2(0.1,0.0);", - "vec3 c,p,n;", - - "float f=1.0;", - "for(int i=0;i<156;i++){", - "if (abs(s.x)<.01||f>maxd) break;", - "f+=s.x;", - "p=prp+scp*f;", - "s=obj0(p);", - "}", - - "if (feps )", - "{", - "if( fire(p) < .0)", - "glowed=true;", - "if(glowed)", - "glow = float(i)/64.;", - "}", - "}", - "return vec4(p,glow);", - "}", - - "//-----------------------------------------------------------------------------", - "// Main functions", - "//-----------------------------------------------------------------------------", - - "void main()", - "{", - "vec2 v = -1.0 + 2.0 * gl_FragCoord.xy / iResolution.xy;", - "v.x *= iResolution.x/iResolution.y;", - "vec3 org = vec3(0.,-2.,4.);", - "vec3 dir = normalize(vec3(v.x*1.6,-v.y,-1.5));", - "vec4 p = Raymarche(org,dir);", - "float glow = p.w;", - "gl_FragColor = mix(vec4(0.), mix(vec4(1.,.5,.1,1.),vec4(0.1,.5,1.,1.),p.y*.02+.4), pow(glow*2.,4.));", - "//gl_FragColor = mix(vec4(1.), mix(vec4(1.,.5,.1,1.),vec4(0.1,.5,1.,1.),p.y*.02+.4), pow(glow*2.,4.));", - - "}" - - ]; - -} - -PIXI.FlameFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.FlameFilter.prototype.constructor = PIXI.FlameFilter; - -Object.defineProperty(PIXI.FlameFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var stars; -var flame; - -function create() { - - flame = game.add.sprite(0, 0, 'texture'); - flame.scale.setTo(10, 10); - - stars = new PIXI.FlameFilter(flame.width, flame.height); - - flame.filters = [stars]; - -} - -function update() { - - stars.iGlobalTime = game.time.totalElapsedSeconds(); - -} diff --git a/examples/wip/filters/flowerFilter.js b/examples/wip/filters/flowerFilter.js deleted file mode 100644 index f737b8d46..000000000 --- a/examples/wip/filters/flowerFilter.js +++ /dev/null @@ -1,89 +0,0 @@ -PIXI.FlowerFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iMouse: { type: 'f3', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by daeken (https://www.shadertoy.com/view/Xdf3R8) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "void main() {", - "float time = iGlobalTime;", - "vec3 p = (gl_FragCoord.xyz / iResolution.y - 0.5) * abs(sin(time/10.0)) * 50.0;", - "float d = sin(length(p)+time), a = sin(mod(atan(p.y, p.x) + time + sin(d+time), 3.1416/3.)*3.), v = a + d, m = sin(length(p)*4.0-a+time);", - "gl_FragColor = vec4(-v*sin(m*sin(-d)+time*.1), v*m*sin(tan(sin(-a))*sin(-a*3.)*3.+time*.5), mod(v,m), time);", - "}"]; - -} - -PIXI.FlowerFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.FlowerFilter.prototype.constructor = PIXI.FlowerFilter; - -Object.defineProperty(PIXI.FlowerFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex00.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.FlowerFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/fractalRayMarchFilter.js b/examples/wip/filters/fractalRayMarchFilter.js deleted file mode 100644 index 890178775..000000000 --- a/examples/wip/filters/fractalRayMarchFilter.js +++ /dev/null @@ -1,175 +0,0 @@ -PIXI.FractalRayMarchFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iMouse: { type: 'f3', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by liamboone (https://www.shadertoy.com/view/4sfGDS) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "const float PI = 3.14159;", - "const float EPS = 0.01;", - - "//Thanks to Inigo Quilez for the wonderful distance functions", - "//[http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm]", - "float sphere(vec3 pos, float rad)", - "{", - "return length(pos)-rad;", - "}", - - "float torus(vec3 pos, vec2 rad)", - "{", - "vec2 q = vec2(length(pos.xz)-rad.x,pos.y);", - "return length(q)-rad.y;", - "}", - - "vec2 cmpSqr(vec2 a)", - "{", - "return vec2(a.x*a.x - a.y*a.y, 2.0*a.x*a.y);", - "}", - - "vec2 cmpMul(vec2 a, vec2 b)", - "{", - "return vec2(a.x*b.x - a.y*b.y, a.x*b.y + b.x*a.y);", - "}", - - "vec3 repeat(vec3 pos, vec3 c)", - "{", - "return mod(pos, c)-0.5*c;", - "}", - - "float map(vec3 pos, out int material)", - "{", - "material = 0;", - "vec3 q = repeat(pos, vec3(10.0));", - "return min(sphere(pos, 2.0), min(max(sphere(q, 1.0),-torus(q,vec2(1.5, 1.0))),torus(q,vec2(1.5, 0.25))));", - "}", - - "vec3 getNormal(vec3 p) {", - "int m;", - "return normalize(vec3(", - "map(p + vec3(EPS, 0, 0), m) - map(p - vec3(EPS, 0, 0), m),", - "map(p + vec3(0, EPS, 0), m) - map(p - vec3(0, EPS, 0), m),", - "map(p + vec3(0, 0, EPS), m) - map(p - vec3(0, 0, EPS), m)));", - "}", - - "void main(void)", - "{", - "float fovy = (70.0+sin(iGlobalTime*0.3)*50.0) / 2.0;", - "float fovy_rad = fovy * PI / 180.0;", - "//Define camera position and view", - "vec3 eye = vec3(-10.0 + 5.0*cos(iGlobalTime), 10.0 + 5.0*sin(iGlobalTime*0.5), 2.0*sin(iGlobalTime*0.1));", - "vec3 view = normalize(vec3(0.0) - eye);", - "vec3 up = normalize(vec3(0.0, 1.0, 0.0));", - "vec3 right = normalize(cross(view, up));", - "up = normalize(cross(right, view));", - - "//Dolly zoom equation from wikipedia.org/wiki/Dolly_zoom", - "float distFromTarget = 10.0;", - "float scale = iResolution.x / iResolution.y / (2.0 * tan(fovy_rad));", - "eye = vec3(0) - view*distFromTarget*scale;", - - - "//Figure out where the ray should point", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - "vec2 real_uv = (uv - 0.5) * 2.0;", - "real_uv *= (iResolution.xy / iResolution.y);", - - "//Then point it there", - "vec3 ray = (view * cos(fovy_rad)) +", - "(up * real_uv.y * sin(fovy_rad)) +", - "(right * real_uv.x * sin(fovy_rad));", - - "ray = normalize(ray);", - - "//Everything starts somewhere", - "vec3 pos = eye;", - "float dist = 999.0;", - "float travel = 0.0;", - "int material;", - - "//Engage!", - "for(int i = 0; i < 100; i ++)", - "{", - "dist = map(pos, material);", - "pos += ray * dist;// * 0.9;", - "travel += dist;// * 0.9;", - "}", - - "vec3 norm = getNormal(pos);", - "gl_FragColor = vec4(mix(vec3(0.0), abs(norm), exp(-0.01*travel)), 1.0);", - "}"]; - -} - -PIXI.FractalRayMarchFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.FractalRayMarchFilter.prototype.constructor = PIXI.FractalRayMarchFilter; - -Object.defineProperty(PIXI.FractalRayMarchFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex00.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.FractalRayMarchFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/heroku.js b/examples/wip/filters/heroku.js deleted file mode 100644 index 45472ccea..000000000 --- a/examples/wip/filters/heroku.js +++ /dev/null @@ -1,167 +0,0 @@ -PIXI.RayTracedBallsFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - resolution: { type: '2f', value: { x: width, y: height }}, - mouse: { type: '2f', value: { x: 0, y: 0 }}, - time: { type: '1f', value: 1 } - }; - - // http://glsl.heroku.com/e#12288.0 - - // Heroku shader conversion - - this.fragmentSrc = [ - "precision mediump float;", - - "// CBS", - "// ported from https://www.shadertoy.com/view/lslGWr", - "// Added some stars: Thanks to http://glsl.heroku.com/e#6904.0", - "// Modified for use", - - "uniform float time;", - "uniform vec2 mouse;", - "uniform vec2 resolution;", - - "// http://www.fractalforums.com/new-theories-and-research/very-simple-formula-for-fractal-patterns/", - "float field(in vec3 p) {", - "float strength = 7. + .03 * log(1.e-6 + fract(sin(time*0.001) * 4373.11));", - "float accum = 0.;", - "float prev = 0.;", - "float tw = 0.;", - "for (int i = 0; i < 24; ++i) {", - "float mag = dot(p, p);", - "p = abs(p) / mag + vec3(-.51, -.4, -1.3);", - "float w = exp(-float(i) / 7.);", - "accum += w * exp(-strength * pow(abs(mag - prev), 2.3));", - "tw += w;", - "prev = mag;", - "}", - "return max(0., 5. * accum / tw - .7);", - "}", - - "float rand(vec2 co) {", - "return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);", - "}", - - "float stars(float slow_time, vec2 position) {", - - "float brightness = 0.;", - - "for (int i = 0; i < 100; i++) {", - - "vec2 rand_pos = vec2(rand(vec2(i)),rand(vec2(i+1)))*2.;", - "float scale = pow(rand(vec2(i+2)),2.);", - - "vec2 l_pos = rand_pos - .15*vec2(sin(slow_time/16.), sin(slow_time/12.))*scale;", - - "l_pos = mod(l_pos,2.)-1.;", - "l_pos *= 1.03;", - - "vec2 dist = abs(l_pos - position);", - "dist.x = min(dist.x,.1);", - "dist.y = min(dist.y,.1);", - - "//float intensity = 1. - (pow(dist.x, .5*scale) + pow(dist.y, .1-.05*scale));", - "float intensity = .0005*scale/sqrt(pow(dist.x,2.)+pow(dist.y,2.));", - "intensity = clamp(intensity * 1., 0., 1.);", - - "brightness = brightness + pow(4. * intensity, 2.);", - "}", - "return brightness;", - "}", - - "vec3 nrand3( vec2 co )", - "{", - "vec3 a = fract( cos( co.x*8.3e-3 + co.y )*vec3(1.3e5, 4.7e5, 2.9e5) );", - "vec3 b = fract( sin( co.x*0.3e-3 + co.y )*vec3(8.1e5, 1.0e5, 0.1e5) );", - "vec3 c = mix(a, b, 1111110.5);", - "return c;", - "}", - - - "void main() {", - "vec2 uv = 2.0 * gl_FragCoord.xy / resolution.xy - 1.0;", - "vec2 uvs = uv * resolution.xy / max(resolution.x, resolution.y);", - "float realtime = time*000.1;", - - "vec3 p = vec3(uvs / 4., 0) + vec3(2., -1.3, -1.);", - "p += 0.15 * vec3(sin(realtime / 16.), sin(realtime / 12.), sin(realtime / 128.));", - - "vec3 p2 = vec3(uvs / (4.+sin(realtime*0.11)*0.2+0.2+sin(realtime*0.15)*0.3+0.4), 1.5) + vec3(2., -1.3, -1.);", - "p2 += 0.15 * vec3(sin(realtime / 16.), sin(realtime / 12.), sin(realtime / 128.));", - - "float t = field(p);", - "float t2 = field(p2);", - "float v = (1. - exp((abs(uv.x) - 10.) * 6.)) * (1. - exp((abs(uv.y) - 1.) * 6.));", - - "vec4 c1 = mix(.4, 1., v) * vec4(1.8 * t * t * t, 1.4 * t * t, t, 1.0);", - "vec4 c2 = mix(.4, 1., v) * vec4((sin(realtime/7.)+1.+uvs.x/16.+uvs.y/32.) * t2 * t2 * t2 * (t+9.)/10., (sin(realtime/11.)+1.-uvs.x/16.-uvs.y/32.) * t2 * t2, t2, sin(realtime/19.)/2.+.5);", - "//c1.b *= mod(gl_FragCoord.y+1.0, 2.0)*1.4;", - "c2.r *= mod(gl_FragCoord.y, 1.0)*7.4;", - "gl_FragColor = (c1 + c2)*.8-.3;//+stars(realtime,uvs);", - "gl_FragColor += vec4(vec3(stars(realtime,uvs)),1.0);", - - "}"]; - - - -} - -PIXI.RayTracedBallsFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.RayTracedBallsFilter.prototype.constructor = PIXI.RayTracedBallsFilter; - -Object.defineProperty(PIXI.RayTracedBallsFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.time.value; - }, - set: function(value) { - this.uniforms.time.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex01.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.RayTracedBallsFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.mouse.value.x = game.input.x; - filter.uniforms.mouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/hueRotationFilter.js b/examples/wip/filters/hueRotationFilter.js deleted file mode 100644 index e48472b9c..000000000 --- a/examples/wip/filters/hueRotationFilter.js +++ /dev/null @@ -1,118 +0,0 @@ -PIXI.HueRotationFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture } - }; - - // Shader by Daniil (https://www.shadertoy.com/view/4sl3DH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "/* Simple hue rotation filter based on article:", - "http://beesbuzz.biz/code/hsv_color_transforms.php", - "*/", - - "#define SPEED 1.0", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - - "float c = cos(iGlobalTime*SPEED);", - "float s = sin(iGlobalTime*SPEED);", - - "mat4 hueRotation =", - "mat4( 0.299, 0.587, 0.114, 0.0,", - "0.299, 0.587, 0.114, 0.0,", - "0.299, 0.587, 0.114, 0.0,", - "0.000, 0.000, 0.000, 1.0) +", - - "mat4( 0.701, -0.587, -0.114, 0.0,", - "-0.299, 0.413, -0.114, 0.0,", - "-0.300, -0.588, 0.886, 0.0,", - "0.000, 0.000, 0.000, 0.0) * c +", - - "mat4( 0.168, 0.330, -0.497, 0.0,", - "-0.328, 0.035, 0.292, 0.0,", - "1.250, -1.050, -0.203, 0.0,", - "0.000, 0.000, 0.000, 0.0) * s;", - - "vec4 pixel = texture2D(iChannel0, uv);", - - "gl_FragColor = pixel * hueRotation;", - - "}"]; - - - -} - -PIXI.HueRotationFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.HueRotationFilter.prototype.constructor = PIXI.HueRotationFilter; - -Object.defineProperty(PIXI.HueRotationFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'assets/pics/ra_einstein.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - // sprite.width = 800; - // sprite.height = 600; - - filter = new PIXI.HueRotationFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/hypnoticRipplesFilter.js b/examples/wip/filters/hypnoticRipplesFilter.js deleted file mode 100644 index d240ae184..000000000 --- a/examples/wip/filters/hypnoticRipplesFilter.js +++ /dev/null @@ -1,110 +0,0 @@ -PIXI.HypnoticRipplesFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture } - }; - - // Shader by Cha (https://www.shadertoy.com/view/ldX3zr) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - - "vec2 center = vec2(0.5,0.5);", - "float speed = 0.035;", - "float invAr = iResolution.y / iResolution.x;", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - - "vec3 col = vec4(uv,0.5+0.5*sin(iGlobalTime),1.0).xyz;", - - "vec3 texcol;", - - "float x = (center.x-uv.x);", - "float y = (center.y-uv.y) *invAr;", - - "//float r = -sqrt(x*x + y*y); //uncoment this line to symmetric ripples", - "float r = -(x*x + y*y);", - "float z = 1.0 + 0.5*sin((r+iGlobalTime*speed)/0.013);", - - "texcol.x = z;", - "texcol.y = z;", - "texcol.z = z;", - - "gl_FragColor = vec4(col*texcol,1.0);", - "//gl_FragColor = vec4(texcol,1.0);", - "}"]; - - - -} - -PIXI.HypnoticRipplesFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.HypnoticRipplesFilter.prototype.constructor = PIXI.HypnoticRipplesFilter; - -Object.defineProperty(PIXI.HypnoticRipplesFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'wip/tex16.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.HypnoticRipplesFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/icosohedronFilter.js b/examples/wip/filters/icosohedronFilter.js deleted file mode 100644 index 35bb6225e..000000000 --- a/examples/wip/filters/icosohedronFilter.js +++ /dev/null @@ -1,220 +0,0 @@ -PIXI.IcosohedronFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture } - }; - - // Shader by WouterVanNifterick (https://www.shadertoy.com/view/ldS3Rh) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "// Tracer code by Ben Weston - 2013", - "// Geometry, colouring and and animation by Wouter van Nifterick 2013", - "// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.", - - "const float pi2 = 6.28318530717958647692;", - - "const float epsilon = .003;", - "const float normalPrecision = .1;", - "const float shadowOffset = .2;", - "const int traceDepth = 50; // takes time", - "const float drawDistance = 150.0;", - "const float stepScale = .9;", - - "const vec3 CamPos = vec3(0,20.0,-20.0);", - "const vec3 CamLook = vec3(0,0,0);", - - "const vec3 lightDir = vec3(0,1,1);", - "const vec3 fillLightDir = vec3(0,0,-1);", - "const vec3 lightColour = vec3(1,.8,.6);", - "const vec3 fillLightColour = vec3(.05,.15,.25);", - - - "float Isosurface( vec3 at )", - "{", - "float res=.6;", - "float n=(1.0+sqrt(5.0))*0.49;", - - "at /= 2.5;", - "if(length(at) < 5.9)", - "{", - "float t =", - "res =2.0 -", - "(cos(at.x + n * at.y) +", - "cos(at.x - n * at.y) +", - "cos(at.y + n * at.z) +", - "cos(at.y - n * at.z) +", - "cos(at.z + n * at.x) +", - "cos(at.z - n * at.x)) ;", - "}", - "return res;", - "}", - - "vec3 Shading( vec3 pos, vec3 norm, float shadow, vec3 rd )", - "{", - "vec3 albedo = vec3(.4);", - - "vec3 l = shadow*lightColour*max(0.0,dot(norm,lightDir));", - "vec3 fl = fillLightColour*(dot(norm,fillLightDir)*.5+.5);", - - "vec3 view = normalize(-rd);", - "vec3 h = normalize(view+lightDir);", - "float specular = pow(max(0.0,dot(h,norm)),200.0);", - "vec3 res = albedo*(l+fl) + shadow*specular*22.0*lightColour*0.1;", - "return res;", - "}", - - - "float Trace( vec3 ro, vec3 rd )", - "{", - "float t = 0.0;", - "float dist = 1.0;", - "for ( int i=0; i < traceDepth; i++ )", - "{", - "if ( abs(dist) < epsilon || t > drawDistance || t < 0.0 )", - "continue;", - "dist = Isosurface( ro+rd*t );", - "t = t+dist*stepScale;", - "}", - - "return t;", - "}", - - "// get normal", - "vec3 GetNormal( vec3 pos )", - "{", - "const vec2 delta = vec2(normalPrecision, 0);", - "vec3 n;", - "n.x = Isosurface( pos + delta.xyy ) - Isosurface( pos - delta.xyy );", - "n.y = Isosurface( pos + delta.yxy ) - Isosurface( pos - delta.yxy );", - "n.z = Isosurface( pos + delta.yyx ) - Isosurface( pos - delta.yyx );", - "return normalize(n);", - "}", - - "// camera function by TekF", - "// compute ray from camera parameters", - "vec3 GetRay( vec3 dir, float zoom, vec2 uv )", - "{", - "uv = uv - .5;", - "uv.x *= iResolution.x/iResolution.y;", - - "dir = zoom*normalize(dir);", - "vec3 right = normalize(cross(vec3(0,1,0),dir));", - "vec3 up = normalize(cross(dir,right));", - - "return dir + right*uv.x + up*uv.y;", - "}", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - - "vec3 camPos = CamPos;", - "vec3 camLook = CamLook;", - - "vec2 camRot = .5*pi2*(iMouse.xy-iResolution.xy*.5)/iResolution.x;", - "camRot += iGlobalTime*0.5;", - "camRot.y = 0.0;", - - "camPos.yz = cos(camRot.y)*camPos.yz* (0.5+sin (iGlobalTime)*0.2) + sin(camRot.y)*camPos.zy*vec2(1,-1);", - "camPos.xz = cos(camRot.x)*camPos.xz + sin(camRot.x)*camPos.zx*vec2(1,-1);", - - "vec3 rd, ro = camPos;", - "rd = GetRay( camLook-camPos, 1.0, uv );", - - "float t = Trace(ro,rd);", - - "vec3 result = vec3(0);", - "if ( t > 0.0 && t < drawDistance )", - "{", - "vec3 pos = ro+t*rd;", - - "vec3 norm = GetNormal(pos);", - - "// shadow test", - "float shadow = 0.0;", - "if ( Trace( pos+lightDir*shadowOffset, lightDir ) < drawDistance )", - "shadow = 0.15;", - - "result = Shading( pos, norm, shadow, rd )*6.0;", - - "// fog", - "result = mix ( vec3(.6+sin(1.0+iGlobalTime)*0.6,.9+cos(iGlobalTime)*0.2,1.1+sin(iGlobalTime)*0.1), result, exp(-t*t*.0005) )*2.0-0.5;", - "result -= distance(vec2(0),pos.xy)*0.03;", - "}", - - "gl_FragColor = vec4( result, 1.0 );", - "}"]; - - - -} - -PIXI.IcosohedronFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.IcosohedronFilter.prototype.constructor = PIXI.IcosohedronFilter; - -Object.defineProperty(PIXI.IcosohedronFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'wip/tex16.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.IcosohedronFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/index.php b/examples/wip/filters/index.php deleted file mode 100644 index 7938ad82b..000000000 --- a/examples/wip/filters/index.php +++ /dev/null @@ -1,109 +0,0 @@ - $value) - { - if (is_array($value) && count($value) > 0) - { - $total += count($value); - } - } - - function getFile() { - - global $files, $dir, $filename, $title, $code; - - if (isset($_GET['d']) && isset($_GET['f'])) - { - $dir = urldecode($_GET['d']); - $filename = urldecode($_GET['d']) . '/' . urldecode($_GET['f']); - $title = urldecode($_GET['t']); - - if (file_exists($filename)) - { - $code = file_get_contents($filename); - $files = dirToArray($dir); - } - } - - } - - function dirToArray($dir) { - - $ignore = array('.', '..', '_site', 'assets', 'states', 'book'); - $result = array(); - $root = scandir($dir); - $dirs = array_diff($root, $ignore); - - foreach ($dirs as $key => $value) - { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) - { - $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); - } - else - { - if (substr($value, -3) == '.js') - { - $result[] = $value; - } - } - } - - return $result; - } - - function printJSLinks($dir, $files) { - - $output = ""; - - foreach ($files as $key => $value) - { - $value2 = substr($value, 0, -3); - $file = urlencode($value); - - $output .= "$value2
"; - } - - return $output; - - } -?> - - - - - phaser - - - - - - - - -
- -

work in progress filters

- - - - - \ No newline at end of file diff --git a/examples/wip/filters/lightbeam_demo.js b/examples/wip/filters/lightbeam_demo.js deleted file mode 100644 index 3802670f6..000000000 --- a/examples/wip/filters/lightbeam_demo.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update }); - -var background; -var filter; - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser2.png'); - game.load.script('light', '../filters/LightBeam.js'); - -} - -function create() { - - var logo = game.add.sprite(game.world.centerX, game.world.centerY, 'phaser'); - logo.anchor.setTo(0.5, 0.5); - - background = game.add.sprite(0, 0); - background.width = 800; - background.height = 600; - - filter = game.add.filter('LightBeam', 800, 600); - - // You have the following values to play with (defaults shown): - filter.alpha = 0.0; - // filter.red = 1.0; - // filter.green = 1.0; - // filter.blue = 2.0; - // filter.thickness = 70.0; - // filter.speed = 1.0; - - background.filters = [filter]; - -} - -function update() { - - filter.update(); - -} diff --git a/examples/wip/filters/mengerTunnelFilter.js b/examples/wip/filters/mengerTunnelFilter.js deleted file mode 100644 index 7e3b16137..000000000 --- a/examples/wip/filters/mengerTunnelFilter.js +++ /dev/null @@ -1,163 +0,0 @@ -PIXI.MengerTunnelFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by fb39ca4 (https://www.shadertoy.com/view/XslGzl) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "const int MAX_RAY_STEPS = 64;", - "const float RAY_STOP_TRESHOLD = 0.0001;", - "const int MENGER_ITERATIONS = 5;", - - "float maxcomp(vec2 v) { return max(v.x, v.y); }", - - "float sdCross(vec3 p) {", - "p = abs(p);", - "vec3 d = vec3(max(p.x, p.y),", - "max(p.y, p.z),", - "max(p.z, p.x));", - "return min(d.x, min(d.y, d.z)) - (1.0 / 3.0);", - "}", - - "float sdCrossRep(vec3 p) {", - "vec3 q = mod(p + 1.0, 2.0) - 1.0;", - "return sdCross(q);", - "}", - - "float sdCrossRepScale(vec3 p, float s) {", - "return sdCrossRep(p * s) / s;", - "}", - - "float scene(vec3 p) {", - "float scale = 1.0;", - "float dist = 0.0;", - "for (int i = 0; i < MENGER_ITERATIONS; i++) {", - "dist = max(dist, -sdCrossRepScale(p, scale));", - "scale *= 3.0;", - "}", - "return dist;", - "}", - - "vec3 hsv2rgb(vec3 c)", - "{", - "vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);", - "vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);", - "return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);", - "}", - - "vec4 colorize(float c) {", - - "float hue = mix(0.6, 1.15, min(c * 1.2 - 0.05, 1.0));", - "float sat = 1.0 - pow(c, 4.0);", - "float lum = c;", - "vec3 hsv = vec3(hue, sat, lum);", - "vec3 rgb = hsv2rgb(hsv);", - "return vec4(rgb, 1.0);", - "}", - - - "void main(void)", - "{", - "vec2 screenPos = gl_FragCoord.xy / iResolution.xy * 2.0 - 1.0;", - "vec2 mousePos = iMouse.xy / iResolution.xy * 2.0 - 1.0;", - - "vec3 cameraPos = vec3(0.16 * sin(iGlobalTime), 0.16 * cos(iGlobalTime), iGlobalTime);", - "//vec3 cameraPos = vec3(0.0);", - "vec3 cameraDir = vec3(0.0, 0.0, 1.0);", - "vec3 cameraPlaneU = vec3(1.0, 0.0, 0.0);", - "vec3 cameraPlaneV = vec3(0.0, 1.0, 0.0) * (iResolution.y / iResolution.x);", - - "vec3 rayPos = cameraPos;", - "vec3 rayDir = cameraDir + screenPos.x * cameraPlaneU + screenPos.y * cameraPlaneV;", - - "rayDir = normalize(rayDir);", - - "float dist = scene(rayPos);", - "int stepsTaken;", - "for (int i = 0; i < MAX_RAY_STEPS; i++) {", - "if (dist < RAY_STOP_TRESHOLD) {", - "continue;", - "}", - "rayPos += rayDir * dist;", - "dist = scene(rayPos);", - "stepsTaken = i;", - "}", - - "vec4 color = colorize(pow(float(stepsTaken) / float(MAX_RAY_STEPS), 0.9));", - - "gl_FragColor = color;", - "}"]; - - -} - -PIXI.MengerTunnelFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.MengerTunnelFilter.prototype.constructor = PIXI.MengerTunnelFilter; - -Object.defineProperty(PIXI.MengerTunnelFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex15.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.MengerTunnelFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/metaBallsFilter.js b/examples/wip/filters/metaBallsFilter.js deleted file mode 100644 index 67cc6c5e4..000000000 --- a/examples/wip/filters/metaBallsFilter.js +++ /dev/null @@ -1,116 +0,0 @@ -PIXI.MetaBallsFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by triggerHLM (https://www.shadertoy.com/view/lsfGDH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "#define stiffness 10.0 // Blobbiness factor (higher = stiffer balls)", - "#define cfalloff 20.0 // Glow factor (higher = sharper, shorter glow)", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - - "// calculate some ball positions (sin is nice for animating)", - "vec2 ballA = vec2(0.5+0.5*sin(iGlobalTime),0.5+0.5*cos(iGlobalTime));", - "vec2 ballB = vec2(0.5+0.4*sin(iGlobalTime),0.5+0.4*cos(iGlobalTime*1.3));", - "vec2 ballC = vec2(0.5+0.4*sin(iGlobalTime*2.0),0.5+0.4*cos(iGlobalTime*1.7));", - - "// calc range-based per-pixel values", - "// subtract from length to make the ball bigger (every pixel closer)", - "// clamp to avoid negative distances and fucky values", - "// invert it so it's closeness to the ball", - "// raise to power to sharpen the edge of the ball (more sudden falloff from 1.0)", - "float r1 = pow(1.0-clamp(length(uv-ballA)-0.1,0.0,1.0),stiffness);", - "float r2 = pow(1.0-clamp(length(uv-ballB)-0.05,0.0,1.0),stiffness);", - "float r3 = pow(1.0-clamp(length(uv-ballC)-0.025,0.0,1.0),stiffness);", - - "// sum for blobbage!", - "float v = r1+r2+r3;", - - "// calculate colour", - "vec3 final = vec3(v,v,v);", - "final.x = pow(v,cfalloff);", - "final.y = pow(v,cfalloff);", - "final.z = pow(v,cfalloff*0.4); // sharpen blue less, for a blue glow", - - "// gimme some pixels baby!", - "gl_FragColor = vec4(final,1.0);", - "}"]; - -} - -PIXI.MetaBallsFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.MetaBallsFilter.prototype.constructor = PIXI.MetaBallsFilter; - -Object.defineProperty(PIXI.MetaBallsFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex07.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.MetaBallsFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/mouseStarFilter.js b/examples/wip/filters/mouseStarFilter.js deleted file mode 100644 index cbf7bf23e..000000000 --- a/examples/wip/filters/mouseStarFilter.js +++ /dev/null @@ -1,100 +0,0 @@ -PIXI.MouseStarFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iMouse: { type: 'f3', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by Danguafer (https://www.shadertoy.com/view/XdB3zw) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec3 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "#define t iGlobalTime/4.0", - - "void main(void) {", - "vec2 p = (2.0*gl_FragCoord.xy-iResolution.xy)/iResolution.y;", - "vec2 mp = iMouse.xy/iResolution.xy*0.5+0.5;", - - "float s = 1.0;", - "for (int i=0; i < 7; i++) {", - "s = max(s,abs(p.x)-0.375);", - "p = abs(p*2.25)-mp*1.25;", - "p *= mat2(cos(t),-sin(t),sin(t),cos(t));", - "}", - - "vec3 col = vec3(4.0,2.0,1.0)/abs(atan(p.y,p.x))/s;", - - "gl_FragColor = vec4(col,1.0);", - "}"]; - -} - -PIXI.MouseStarFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.MouseStarFilter.prototype.constructor = PIXI.MouseStarFilter; - -Object.defineProperty(PIXI.MouseStarFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex00.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.MouseStarFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/mysteryVortexFilter.js b/examples/wip/filters/mysteryVortexFilter.js deleted file mode 100644 index c8915bc7e..000000000 --- a/examples/wip/filters/mysteryVortexFilter.js +++ /dev/null @@ -1,95 +0,0 @@ -PIXI.MysteryVortexFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel1: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by xeron_iris (https://www.shadertoy.com/view/XdXGz7) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "void main(void)", - "{", - "vec2 uv = (gl_FragCoord.xy - (iResolution.xy/2.0)) / iResolution.xy;", - - "float dist = sqrt(uv.x*uv.x+uv.y*uv.y);", - - "float distr = ((sin(iGlobalTime)+1.0)-dist) * sin(atan(uv.x, uv.y)*7.0+iGlobalTime*4.01+sin(dist*(cos(iGlobalTime*0.3)+0.25)*40.0));", - "float distg = ((sin(iGlobalTime*0.9)+1.0)-dist) * sin(atan(uv.x, uv.y)*8.0+iGlobalTime*3.41+sin(dist*(cos(iGlobalTime*0.25)+0.25)*40.0));", - "float distb = ((sin(iGlobalTime*1.15)+1.0)-dist) * sin(atan(uv.x, uv.y)*9.0+iGlobalTime*4.36+sin(dist*(cos(iGlobalTime*0.33)+0.25)*40.0));", - - "gl_FragColor = vec4(distr+distg-distb, distg+distb-distr, distb+distr-distg, 1.0);", - "}"]; - -} - -PIXI.MysteryVortexFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.MysteryVortexFilter.prototype.constructor = PIXI.MysteryVortexFilter; - -Object.defineProperty(PIXI.MysteryVortexFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex00.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.MysteryVortexFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/planeDeformationFilter.js b/examples/wip/filters/planeDeformationFilter.js deleted file mode 100644 index ad52b55d1..000000000 --- a/examples/wip/filters/planeDeformationFilter.js +++ /dev/null @@ -1,116 +0,0 @@ -PIXI.PlaneDeformationFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, textureData: { repeat: true } } - }; - - // Shader by cce (https://www.shadertoy.com/view/XsXGWM) - -// "vec4 blips = texture2D(iChannel1, maa);", -// "vec4 mixer = texture2D(iChannel1, maa2);", - - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "void main(void)", - "{", - "float t = iGlobalTime;", - - "/*", - "float ang = t;", - "mat2 rotation = mat2(cos(ang), sin(ang),", - "-sin(ang), cos(ang));", - "*/", - - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - "vec2 texcoord = gl_FragCoord.xy / vec2(iResolution.y);", - - "texcoord.y -= t*0.2;", - - "float zz = 1.0/(1.0-uv.y*1.7);", - "texcoord.y -= zz * sign(zz);", - - "vec2 maa = texcoord.xy * vec2(zz, 1.0) - vec2(zz, 0.0) ;", - "vec2 maa2 = (texcoord.xy * vec2(zz, 1.0) - vec2(zz, 0.0))*0.3 ;", - "vec4 stone = texture2D(iChannel0, maa);", - "vec4 blips = texture2D(iChannel0, maa);", - "vec4 mixer = texture2D(iChannel0, maa2);", - - "float shade = abs(1.0/zz);", - - "vec3 outp = mix(shade*stone.rgb, mix(1.0, shade, abs(sin(t+maa.y-sin(maa.x))))*blips.rgb, min(1.0, pow(mixer.g*2.1, 2.0)));", - "gl_FragColor = vec4(outp,1.0);", - "}"]; - -} - -PIXI.PlaneDeformationFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.PlaneDeformationFilter.prototype.constructor = PIXI.PlaneDeformationFilter; - -Object.defineProperty(PIXI.PlaneDeformationFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex03.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.PlaneDeformationFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/plasma3DFilter.js b/examples/wip/filters/plasma3DFilter.js deleted file mode 100644 index 27cbfeb8c..000000000 --- a/examples/wip/filters/plasma3DFilter.js +++ /dev/null @@ -1,160 +0,0 @@ -PIXI.Plasma3DFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates } - }; - - // Shader by Optimus (https://www.shadertoy.com/view/Mss3zn) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "// Dark Chocolate Cave Plasma by Optimus", - - "#ifdef GL_ES", - "precision mediump float;", - "#endif", - - "float time;", - "vec2 mouse;", - "vec2 resolution;", - - "const int iters = 256;", - - "const float origin_z = 0.0;", - "const float plane_z = 4.0;", - "const float far_z = 64.0;", - - "const float step = (far_z - plane_z) / float(iters) * 0.025;", - - "const float color_bound = 0.0;", - "const float upper_bound = 1.0;", - - "const float scale = 32.0;", - - "const float disp = 0.25;", - - "float calc_this(vec3 p, float disx, float disy, float disz)", - "{", - "float c = sin(sin((p.x + disx) * sin(sin(p.z + disz)) + time) + sin((p.y + disy) * cos(p.z + disz) + 2.0 * time) + sin(3.0*p.z + disz + 3.5 * time) + sin((p.x + disx) + sin(p.y + disy + 2.5 * (p.z + disz - time) + 1.75 * time) - 0.5 * time));", - "return c;", - "}", - - "vec3 get_intersection()", - "{", - "vec2 position = (gl_FragCoord.xy / resolution.xy - 0.5) * scale;", - - "vec3 pos = vec3(position.x, position.y, plane_z);", - "vec3 origin = vec3(0.0, 0.0, origin_z);", - - "vec3 dir = pos - origin;", - "vec3 dirstep = normalize(dir) * step;", - - "dir = normalize(dir) * plane_z;", - - - "float c;", - - "for (int i=0; i color_bound)", - "{", - "break;", - "}", - - "dir = dir + dirstep;", - "}", - - "return dir;", - "}", - - - "void main()", - "{", - "time = iGlobalTime;", - "mouse = vec2(iMouse);", - "resolution = vec2(iResolution);", - - "vec3 p = get_intersection();", - "float dx = color_bound - calc_this(p, disp, 0.0, 0.0);", - "float dy = color_bound - calc_this(p, 0.0, disp, 0.0);", - - "vec3 du = vec3(disp, 0.0, dx);", - "vec3 dv = vec3(0.0, disp, dy);", - "vec3 normal = normalize(cross(du, dv));", - - "vec3 light = normalize(vec3(0.0, 0.0, 1.0));", - "float l = dot(normal, light);", - - "float cc = pow(l, 2.0);", - "gl_FragColor = vec4(cc*0.8, cc*0.5, cc*0.8, cc);", - "}"]; - -} - -PIXI.Plasma3DFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.Plasma3DFilter.prototype.constructor = PIXI.Plasma3DFilter; - -Object.defineProperty(PIXI.Plasma3DFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.Plasma3DFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/plasmaBeamFilter.js b/examples/wip/filters/plasmaBeamFilter.js deleted file mode 100644 index 7b980de23..000000000 --- a/examples/wip/filters/plasmaBeamFilter.js +++ /dev/null @@ -1,96 +0,0 @@ -PIXI.PlasmaBeamFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates } - }; - - // Shader by 4rknova (https://www.shadertoy.com/view/Xsl3WH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "#ifdef GL_ES", - "precision highp float;", - "#endif", - - "#define AMPLITUDE 0.19", - "#define WVELOCITY 1.0", - "#define WAVEWIDTH 2.0", - "#define THICKNESS 0.5", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - - "float h = sin((uv.x * WAVEWIDTH + iGlobalTime * WVELOCITY) * 2.5) * AMPLITUDE;", - "float f = pow(THICKNESS * abs(0.1 / (uv.y * 2.0 - 1.0 + h)), 2.0);", - - "gl_FragColor = vec4(0.0, 0.0, f, 1.0);", - "}"]; - -} - -PIXI.PlasmaBeamFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.PlasmaBeamFilter.prototype.constructor = PIXI.PlasmaBeamFilter; - -Object.defineProperty(PIXI.PlasmaBeamFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.PlasmaBeamFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/plasmaFilter.js b/examples/wip/filters/plasmaFilter.js deleted file mode 100644 index 90f80c624..000000000 --- a/examples/wip/filters/plasmaFilter.js +++ /dev/null @@ -1,100 +0,0 @@ -PIXI.PlasmaFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates } - }; - - // Shader by TriggerHLM (https://www.shadertoy.com/view/MdXGDH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "const float PI = 3.14159265;", - - "float time = iGlobalTime *0.2;", - - "void main(void ) {", - - "float color1, color2, color;", - - "color1 = (sin(dot(gl_FragCoord.xy,vec2(sin(time*3.0),cos(time*3.0)))*0.02+time*3.0)+1.0)/2.0;", - - "vec2 center = vec2(640.0/2.0, 360.0/2.0) + vec2(640.0/2.0*sin(-time*3.0),360.0/2.0*cos(-time*3.0));", - - "color2 = (cos(length(gl_FragCoord.xy - center)*0.03)+1.0)/2.0;", - - "color = (color1+ color2)/2.0;", - - "float red = (cos(PI*color/0.5+time*3.0)+1.0)/2.0;", - "float green = (sin(PI*color/0.5+time*3.0)+1.0)/2.0;", - "float blue = (sin(+time*3.0)+1.0)/2.0;", - - "gl_FragColor = vec4(red, green, blue, 1.0);", - "}" - ]; - -} - -PIXI.PlasmaFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.PlasmaFilter.prototype.constructor = PIXI.PlasmaFilter; - -Object.defineProperty(PIXI.PlasmaFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var plasma; -var container; - -function create() { - - game.stage.backgroundColor = '#000000'; - - container = game.add.sprite(0, 0, 'texture'); - container.width = 800; - container.height = 600; - - plasma = new PIXI.PlasmaFilter(container.width, container.height); - - container.filters = [plasma]; - -} - -function update() { - - plasma.iGlobalTime = game.time.totalElapsedSeconds(); - -} diff --git a/examples/wip/filters/plasmaFlowerFilter.js b/examples/wip/filters/plasmaFlowerFilter.js deleted file mode 100644 index ef5be7734..000000000 --- a/examples/wip/filters/plasmaFlowerFilter.js +++ /dev/null @@ -1,112 +0,0 @@ -PIXI.PlasmaFlowerFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates } - }; - - // Shader by epsilum (https://www.shadertoy.com/view/Xdf3zH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "float addFlower(float x, float y, float ax, float ay, float fx, float fy)", - "{", - "float xx=(x+sin(iGlobalTime*fx)*ax)*8.0;", - "float yy=(y+cos(iGlobalTime*fy)*ay)*8.0;", - "float angle = atan(yy,xx);", - "float zz = 1.5*(cos(18.0*angle)*0.5+0.5) / (0.7 * 3.141592) + 1.2*(sin(15.0*angle)*0.5+0.5)/ (0.7 * 3.141592);", - - "return zz;", - "}", - - "void main(void)", - "{", - "vec2 xy=(gl_FragCoord.xy/iResolution.x)*2.0-vec2(1.0,iResolution.y/iResolution.x);", - - "float x=xy.x;", - "float y=xy.y;", - - "float p1 = addFlower(x, y, 0.8, 0.9, 0.95, 0.85);", - "float p2 = addFlower(x, y, 0.7, 0.9, 0.42, 0.71);", - "float p3 = addFlower(x, y, 0.5, 1.0, 0.23, 0.97);", - "float p4 = addFlower(x, y, 0.8, 0.5, 0.81, 1.91);", - - "float p=clamp((p1+p2+p3+p4)*0.25, 0.0, 1.0);", - - "vec4 col;", - "if (p < 0.5)", - "col=vec4(mix(0.0,1.0,p*2.0), mix(0.0,0.63,p*2.0), 0.0, 1.0);", - "else if (p >= 0.5 && p <= 0.75)", - "col=vec4(mix(1.0, 1.0-0.32, (p-0.5)*4.0), mix(0.63, 0.0, (p-0.5)*4.0), mix(0.0,0.24,(p-0.5)*4.0), 1.0);", - "else", - "col=vec4(mix(0.68, 0.0, (p-0.75)*4.0), 0.0, mix(0.24, 0.0, (p-0.75)*4.0), 1.0);", - - "gl_FragColor = col;", - "}"]; - -} - -PIXI.PlasmaFlowerFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.PlasmaFlowerFilter.prototype.constructor = PIXI.PlasmaFlowerFilter; - -Object.defineProperty(PIXI.PlasmaFlowerFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.PlasmaFlowerFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/plasma_demo.js b/examples/wip/filters/plasma_demo.js deleted file mode 100644 index dcdcb8c5e..000000000 --- a/examples/wip/filters/plasma_demo.js +++ /dev/null @@ -1,43 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -var background; -var filter; - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser2.png'); - game.load.script('fire', '../filters/Plasma.js'); - -} - -function create() { - - background = game.add.sprite(0, 0); - background.width = 800; - background.height = 600; - - filter = game.add.filter('Plasma', 800, 600); - - // You have the following values to play with (defaults shown below): - - // filter.size = 0.03; - // filter.redShift = 0.5; - // filter.greenShift = 0.5; - // filter.blueShift = 0.9; - - background.filters = [filter]; - - var logo = game.add.sprite(game.world.centerX, game.world.centerY, 'phaser'); - logo.anchor.setTo(0.5, 0.5); - -} - -function update() { - - filter.update(); - - // Uncomment for coolness :) - // filter.blueShift -= 0.001; - -} diff --git a/examples/wip/filters/pulsingInterferenceFilter.js b/examples/wip/filters/pulsingInterferenceFilter.js deleted file mode 100644 index 63e3713b6..000000000 --- a/examples/wip/filters/pulsingInterferenceFilter.js +++ /dev/null @@ -1,123 +0,0 @@ -PIXI.PulsingInterferenceFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by knatten (https://www.shadertoy.com/view/lssGR8) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "float PI = 3.14159265358979323846264;", - - "vec2 warp(in vec2 xy)", - "{", - "float amount = 0.3*pow(sin(iGlobalTime*2.0), 20.0);", - "return vec2(xy.x + sin(xy.x*10.0)*amount*sin(iGlobalTime),", - "xy.y + cos(xy.y*10.0)*amount*sin(iGlobalTime));", - "}", - - "float distance(in vec2 uv, in float x, in float y)", - "{", - "return sqrt(pow(abs(uv.x - x), 2.0) + pow(abs(uv.y - y), 2.0));", - "}", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - "uv = warp(uv);", - - "float x_1 = sin(iGlobalTime*1.5);", - "float y_1 = cos(iGlobalTime);", - "float x_2 = cos(iGlobalTime);", - "float y_2 = sin(iGlobalTime);", - - "float dist_1 = distance(uv, x_1, y_1);", - "float dist_2 = distance(uv, x_2, y_2);", - - "float t = sin(iGlobalTime);//mod(iGlobalTime*100.0, 100.0)/100.0;", - "float c1 = sin(dist_1*50.0) * sin(dist_2*50.0);", - "float red = c1*t;", - "float blue = sin(dist_1*50.0) * sin(dist_1*150.0);", - "float green = c1*(1.0-t);", - "vec3 color = vec3(red, green, blue);", - - "vec3 flash = vec3(pow(sin(iGlobalTime*2.0),20.0));", - "color += flash;", - "gl_FragColor = vec4(color, 1.0);", - "}"]; - - - -} - -PIXI.PulsingInterferenceFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.PulsingInterferenceFilter.prototype.constructor = PIXI.PulsingInterferenceFilter; - -Object.defineProperty(PIXI.PulsingInterferenceFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex01.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.PulsingInterferenceFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/rayTracedBallsFilter.js b/examples/wip/filters/rayTracedBallsFilter.js deleted file mode 100644 index 33cc5e8e4..000000000 --- a/examples/wip/filters/rayTracedBallsFilter.js +++ /dev/null @@ -1,220 +0,0 @@ -PIXI.RayTracedBallsFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iMouse: { type: 'f3', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by benito_luna (https://www.shadertoy.com/view/MdX3Ws) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "precision highp float;", - "precision highp int;", - - "const float PI = 3.14159265359;", - - "int T(vec3 o,vec3 d, out float t, out vec3 n){", - - "t=10000.;", - "int m=0;", - "float p=-o.z/d.z;", - "if(.010.){", - "//It does, compute the distance camera-sphere", - "float s=-b-sqrt(q);", - - "if(s.01)", - "{", - "// So far this is the minimum distance, save it. And also", - "// compute the bouncing ray vector into 'n'", - "t=s,", - "n=normalize(p2+d*t),", - "m=2;", - "}", - "}", - "}", - "return m;", - "}", - - "const float PI_2_DIV_3 = 1.0471975512;", - - "vec3 S(in vec3 o,in vec3 d, vec2 uv)", - "{", - "float t;", - "vec3 n;", - - "vec3 cumulated_color = vec3(0.);", - - "//Search for an intersection ray Vs World.", - "int m=T(o,d,t,n);", - "float attenuationFactor = 1.0;", - - "float f = 0.;", - "for(int i = 0; i<3; i++) //Max recursivity - 3 bounces", - "{", - "if(0==m) // m==0", - "{", - "return ( cumulated_color + attenuationFactor * vec3(.7,.6,1)*pow(1.-d.z,4.));", - "}", - - "vec3 h = o+d*t; // h = intersection coordinate", - "vec3 l = normalize(vec3(9.,9.,16.)+h*-1.); // 'l' = direction to light (with random delta for soft-shadows).", - "vec3 r = d+n*(dot(n,d)*-2.); // r = The half-vector", - - "//Calculated the lambertian factor", - "float b=dot(l,n);", - - "//Calculate illumination factor (lambertian coefficient > 0 or in shadow)?", - "if(b<0.||T(h,l,t,n) !=0)", - "b=0.;", - - "// Calculate the color 'p' with diffuse and specular component", - "float p= 0.;", - "if (b!=0.)", - "{", - "p = pow(dot(l,r),99.);", - "}", - - "if(m==1){", - - "h=h*.2; //No sphere was hit and the ray was going downward: Generate a floor color", - "float cond = (float(ceil(h.x + iGlobalTime)+ceil(h.y+iGlobalTime)));", - "//if odd", - "if (fract(cond/2.) == 0.)", - "return (cumulated_color+attenuationFactor *vec3(3.,1.,1.)*(b*0.2+0.1));", - "else", - "return (cumulated_color+attenuationFactor*vec3(3.,3.,3.)*(b*0.2+0.1));", - "}", - "cumulated_color += attenuationFactor*vec3(p);", - "attenuationFactor *= 0.5;", - "o = h;", - "d = r;", - "m=T(h,r,t,n);", - "f++;", - "}", - "return vec3(0.0);", - "}", - - "const float inv_256 = 0.00390625;", - - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy; //some optimization here to do", - "vec3 g=normalize(vec3(-6.,-16.,0.)); // Camera direction", - "vec3 a=normalize(cross(g,vec3(0.,0.,1.)))*.002; // Camera up vector...Seem Z is pointing up :/ WTF !", - "vec3 b=normalize(cross(a,g))*.002; // The right vector, obtained via traditional cross-product", - "vec3 c=(a+b)*-256.+g;", - "vec3 p= vec3(13,13,13); // Default pixel color is almost pitch black", - "highp vec3 t=a*0.5*99.+b*0.5*99.;", - "p=64.*S(vec3(17.,16.,8.)+t,normalize(t*-1.+(a*(gl_FragCoord.x)+b*(gl_FragCoord.y)+c)*16.), uv)*3.5+p; // +p for color accumulation", - "gl_FragColor = vec4(p * inv_256,1.0);", - - "}"]; - - -} - -PIXI.RayTracedBallsFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.RayTracedBallsFilter.prototype.constructor = PIXI.RayTracedBallsFilter; - -Object.defineProperty(PIXI.RayTracedBallsFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex07.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.RayTracedBallsFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/retroPlasmaFilter.js b/examples/wip/filters/retroPlasmaFilter.js deleted file mode 100644 index 0060e4d0f..000000000 --- a/examples/wip/filters/retroPlasmaFilter.js +++ /dev/null @@ -1,117 +0,0 @@ -PIXI.RetroPlasmaFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates } - }; - - // Oldskool plasm shader. (c) Victor Korsun, bitekas@gmail.com; 1996-2013. - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "// Oldskool plasm shader. (c) Victor Korsun, bitekas@gmail.com; 1996-2013.", - "//", - "// Attribution-ShareAlike CC License.", - - "//----------------", - "const int ps = 10; // use values > 1..10 for oldskool", - "//----------------", - - - "void main(void)", - "{", - "float x = gl_FragCoord.x / iResolution.x * 640.;", - "float y = gl_FragCoord.y / iResolution.y * 480.;", - - "if (ps > 0)", - "{", - "x = float(int(x / float(ps)) * ps);", - "y = float(int(y / float(ps)) * ps);", - "}", - - "float mov0 = x+y+sin(iGlobalTime)*10.+sin(x/90.)*70.+iGlobalTime*2.;", - "float mov1 = (mov0 / 5. + sin(mov0 / 30.))/ 10. + iGlobalTime * 3.;", - "float mov2 = mov1 + sin(mov1)*5. + iGlobalTime*1.0;", - "float cl1 = sin(sin(mov1/4. + iGlobalTime)+mov1);", - "float c1 = cl1 +mov2/2.-mov1-mov2+iGlobalTime;", - "float c2 = sin(c1+sin(mov0/100.+iGlobalTime)+sin(y/57.+iGlobalTime/50.)+sin((x+y)/200.)*2.);", - "float c3 = abs(sin(c2+cos((mov1+mov2+c2) / 10.)+cos((mov2) / 10.)+sin(x/80.)));", - - "float dc = float(16-ps);", - - "if (ps > 0)", - "{", - "cl1 = float(int(cl1*dc))/dc;", - "c2 = float(int(c2*dc))/dc;", - "c3 = float(int(c3*dc))/dc;", - "}", - - "gl_FragColor = vec4( cl1,c2,c3,1.0);", - "}"]; - -} - -PIXI.RetroPlasmaFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.RetroPlasmaFilter.prototype.constructor = PIXI.RetroPlasmaFilter; - -Object.defineProperty(PIXI.RetroPlasmaFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.RetroPlasmaFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/rotationalFractalsFilter.js b/examples/wip/filters/rotationalFractalsFilter.js deleted file mode 100644 index 796df4392..000000000 --- a/examples/wip/filters/rotationalFractalsFilter.js +++ /dev/null @@ -1,104 +0,0 @@ -PIXI.RotationalFractalsFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by gleurop (https://www.shadertoy.com/view/MsXGRS) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "vec3 hsv(in float h, in float s, in float v) {", - "return mix(vec3(1.0), clamp((abs(fract(h + vec3(3, 2, 1) / 3.0) * 6.0 - 3.0) - 1.0), 0.0 , 1.0), s) * v;", - "}", - - "void main() {", - "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / iResolution.xy;", - "p.x *= iResolution.x / iResolution.y;", - "vec2 c = vec2(-iGlobalTime*0.154, iGlobalTime*0.2485);", - "float d = 1.0;", - "vec3 col = vec3(0);", - "float t = iGlobalTime;", - "for (int i = 0; i < 20; i++) {", - "float r = length(p);", - "p /= r;", - "p = asin(sin(p/r + c));", - "col += hsv(r, max(1.0-dot(p,p), 0.0), 1.0);", - "}", - "gl_FragColor = vec4(sin(col)*0.5+0.5,", - "1.0);", - "}"]; - - -} - -PIXI.RotationalFractalsFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.RotationalFractalsFilter.prototype.constructor = PIXI.RotationalFractalsFilter; - -Object.defineProperty(PIXI.RotationalFractalsFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex07.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.RotationalFractalsFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/rotoZoomerFilter.js b/examples/wip/filters/rotoZoomerFilter.js deleted file mode 100644 index 7acc04f24..000000000 --- a/examples/wip/filters/rotoZoomerFilter.js +++ /dev/null @@ -1,117 +0,0 @@ -PIXI.RotoZoomerFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iMouse: { type: '3f', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, textureData: { repeat: true } } - }; - - // Shader by triggerHLM (https://www.shadertoy.com/view/lsfGDH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "float time=iGlobalTime*0.2;", - - - "float pi = 3.14159265;", - - - "void main( void )", - "{", - - "vec2 position = vec2(640.0/2.0+640.0/2.0*sin(time*2.0), 360.0/2.0+360.0/2.0*cos(time*3.0));", - "vec2 position2 = vec2(640.0/2.0+640.0/2.0*sin((time+2000.0)*2.0), 360.0/2.0+360.0/2.0*cos((time+2000.0)*3.0));", - - - "vec2 offset = vec2(640.0/2.0, 360.0/2.0) ;", - "vec2 offset2 = vec2(6.0*sin(time*1.1), 3.0*cos(time*1.1));", - - "vec2 oldPos = (gl_FragCoord.xy-offset);", - - "float angle = time*2.0;", - - "vec2 newPos = vec2(oldPos.x *cos(angle) - oldPos.y *sin(angle),", - "oldPos.y *cos(angle) + oldPos.x *sin(angle));", - - - "newPos = (newPos)*(0.0044+0.004*sin(time*3.0))-offset2;", - "vec2 temp = newPos;", - "newPos.x = temp.x + 0.4*sin(temp.y*2.0+time*8.0);", - "newPos.y = (-temp.y + 0.4*sin(temp.x*2.0+time*8.0));", - "vec4 final = texture2D(iChannel0,newPos);", - "//final = texture2D(texCol,gl_FragCoord.xy*vec2(1.0/640, -1.0/360));", - "gl_FragColor = vec4(final.xyz, 1.0);", - - "}"]; - - -} - -PIXI.RotoZoomerFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.RotoZoomerFilter.prototype.constructor = PIXI.RotoZoomerFilter; - -Object.defineProperty(PIXI.RotoZoomerFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex15.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.RotoZoomerFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/shadertoy-effect.js b/examples/wip/filters/shadertoy-effect.js deleted file mode 100644 index 552b50edc..000000000 --- a/examples/wip/filters/shadertoy-effect.js +++ /dev/null @@ -1,1200 +0,0 @@ -var vsSource = [ - "attribute vec2 pos;", - "void main()", - "{", - "gl_Position = vec4(pos.x,pos.y,0.0,1.0);", - "}" - ].join("\n"); - - -var fsSource = [ - "void main()", - "{", - "gl_FragColor = vec4(0.0,0.0,0.0,1.0);", - "}" - ].join("\n"); - -//-------------------------------------- - -function createGLTexture( ctx, image, format, texture ) -{ - if( ctx==null ) return; - - ctx.bindTexture( ctx.TEXTURE_2D, texture); - ctx.pixelStorei( ctx.UNPACK_FLIP_Y_WEBGL, false ); - ctx.texImage2D( ctx.TEXTURE_2D, 0, format, ctx.RGBA, ctx.UNSIGNED_BYTE, image); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR_MIPMAP_LINEAR); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.REPEAT); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.REPEAT); - ctx.generateMipmap(ctx.TEXTURE_2D); - ctx.bindTexture(ctx.TEXTURE_2D, null); -} - -function createGLTextureLinear( ctx, image, texture ) -{ - if( ctx==null ) return; - - ctx.bindTexture( ctx.TEXTURE_2D, texture); - ctx.pixelStorei( ctx.UNPACK_FLIP_Y_WEBGL, false ); - ctx.texImage2D( ctx.TEXTURE_2D, 0, ctx.RGBA, ctx.RGBA, ctx.UNSIGNED_BYTE, image); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE); - ctx.bindTexture(ctx.TEXTURE_2D, null); -} - - -function createGLTextureNearestRepeat( ctx, image, texture ) -{ - if( ctx==null ) return; - - ctx.bindTexture(ctx.TEXTURE_2D, texture); - ctx.pixelStorei( ctx.UNPACK_FLIP_Y_WEBGL, false ); - ctx.texImage2D(ctx.TEXTURE_2D, 0, ctx.RGBA, ctx.RGBA, ctx.UNSIGNED_BYTE, image); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.NEAREST); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.NEAREST); - ctx.bindTexture(ctx.TEXTURE_2D, null); -} - -function createGLTextureNearest( ctx, image, texture ) -{ - if( ctx==null ) return; - - ctx.bindTexture(ctx.TEXTURE_2D, texture); - ctx.pixelStorei( ctx.UNPACK_FLIP_Y_WEBGL, false ); - ctx.texImage2D(ctx.TEXTURE_2D, 0, ctx.RGBA, ctx.RGBA, ctx.UNSIGNED_BYTE, image); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.NEAREST); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.NEAREST); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE); - ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE); - - ctx.bindTexture(ctx.TEXTURE_2D, null); -} - -function createAudioTexture( ctx, texture ) -{ - if( ctx==null ) return; - - ctx.bindTexture( ctx.TEXTURE_2D, texture ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE) ; - ctx.texImage2D( ctx.TEXTURE_2D, 0, ctx.LUMINANCE, 512, 2, 0, ctx.LUMINANCE, ctx.UNSIGNED_BYTE, null); - ctx.bindTexture( ctx.TEXTURE_2D, null); -} - -function createKeyboardTexture( ctx, texture ) -{ - if( ctx==null ) return; - - ctx.bindTexture( ctx.TEXTURE_2D, texture ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.NEAREST ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.NEAREST ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE ); - ctx.texParameteri( ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE) ; - ctx.texImage2D( ctx.TEXTURE_2D, 0, ctx.LUMINANCE, 256, 2, 0, ctx.LUMINANCE, ctx.UNSIGNED_BYTE, null); - ctx.bindTexture( ctx.TEXTURE_2D, null); -} - - -function Effect( ac, gl, xres, yres, callback, obj, forceMuted, forcePaused) -{ - this.mAudioContext = ac; - this.mNoAudioMessageShowed = false; - this.mGLContext = gl; - this.mQuadVBO = null; - this.mProgram = null; - this.mXres = xres; - this.mYres = yres; - this.mInputs = new Array(4); - this.mInputs[0] = null; - this.mInputs[1] = null; - this.mInputs[2] = null; - this.mInputs[3] = null; - this.mTextureCallbackFun = callback; - this.mTextureCallbackObj = obj; - this.mSource = null; - this.mForceMuted = forceMuted; - this.mForcePaused = forcePaused; - this.mSupportsDerivatives = false; - - //------------- - if( gl==null ) return; - - var ext = gl.getExtension('OES_standard_derivatives'); - this.mSupportsDerivatives = (ext != null); - - if( this.mSupportsDerivatives ) - { - gl.hint( ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES, gl.NICEST ); - } - - var ext2 = gl.getExtension('OES_texture_float'); - this.mSupportTextureFloat = (ext2 != null ); - - var vertices = new Float32Array( [ -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0] ); - - this.mQuadVBO = gl.createBuffer(); - gl.bindBuffer(gl.ARRAY_BUFFER, this.mQuadVBO); - gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); - - var res = this.NewShader(fsSource); - - this.DetermineShaderPrecission(); - - this.MakeHeader(); -} - -Effect.prototype.DestroyInput = function( id ) -{ - if( this.mInputs[id]==null ) return; - if( this.mGLContext== null ) return; - - var gl = this.mGLContext; - if( this.mInputs[id].mInfo.mType=="texture" ) - { - gl.deleteTexture( this.mInputs[id].globject ); - } - else if( this.mInputs[id].mInfo.mType=="slideshow" ) - { - gl.deleteTexture( this.mInputs[id].globject ); - } - else if( this.mInputs[id].mInfo.mType=="webcam" ) - { - gl.deleteTexture( this.mInputs[id].globject ); - } - else if( this.mInputs[id].mInfo.mType=="video" ) - { - this.mInputs[id].video.pause(); - this.mInputs[id].video = null; - gl.deleteTexture( this.mInputs[id].globject ); - } - else if( this.mInputs[id].mInfo.mType=="music" ) - { - this.mInputs[id].audio.pause(); - this.mInputs[id].audio = null; - gl.deleteTexture( this.mInputs[id].globject ); - } - else if( this.mInputs[id].mInfo.mType=="cubemap" ) - { - gl.deleteTexture( this.mInputs[id].globject ); - } - else if( this.mInputs[id].mInfo.mType=="keyboard" ) - { - gl.deleteTexture( this.mInputs[id].globject ); - } - - this.mInputs[id] = null; -} - - - -Effect.prototype.NewTexture = function( slot, url ) -{ - var me = this; - var gl = this.mGLContext; - - var texture = null; - - if (url!=null && url.mType=="webcam" && this.mForceMuted) - { - url.mType = "texture"; - } - - if( url==null ) - { - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( this.mTextureCallbackObj, slot, null, false, true, 0, -1.0 ); - return false; - } - else if( url.mType=="texture" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = (gl!=null) ? gl.createTexture() : null; - texture.loaded = false; - texture.image = new Image(); - texture.image.crossOrigin = ''; - texture.image.onload = function() - { - var format = gl.RGBA; - if( url.mSrc=="/presets/tex15.png" || url.mSrc=="/presets/tex17.png" ) - format = gl.LUMINANCE; - - if( url.mSrc=="/presets/tex14.png" ) - createGLTextureNearest( gl, texture.image, texture.globject ); - else if( url.mSrc=="/presets/tex15.png" ) - createGLTextureNearestRepeat( gl, texture.image, texture.globject ); - else - createGLTexture( gl, texture.image, format, texture.globject ); - - texture.loaded = true; - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, texture.image, true, true, 0, -1.0 ); - } - texture.image.src = url.mSrc; - } - else if( url.mType=="slideshow" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = (gl!=null) ? gl.createTexture() : null; - texture.loaded = false; - texture.image = new Image(); - texture.image.crossOrigin = ''; - texture.image.onload = function() - { - createGLTexture( gl, texture.image, gl.RGBA, texture.globject ); - texture.loaded = true; - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, texture.image, true, true, 3, -1.0 ); - } - texture.slideshow = {}; - texture.slideshow.mCurrentSlide = 0; - texture.slideshow.mNewTextureReady = false; - var urlSlide = url.mSrc.replace("??","00"); - texture.image.src = urlSlide; - } - else if( url.mType=="cubemap" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = (gl!=null) ? gl.createTexture() : null; - texture.loaded = false; - texture.image = [ new Image(), new Image(), new Image(), new Image(), new Image(), new Image() ]; - - gl.bindTexture( gl.TEXTURE_CUBE_MAP, texture.globject ); - gl.texParameteri( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR ); - gl.texParameteri( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR ); - gl.bindTexture( gl.TEXTURE_CUBE_MAP, null ); - - texture.loaded = true; - - for( var i=0; i<6; i++ ) - { - texture.image[i].mId = i; - texture.image[i].crossOrigin = ''; - texture.image[i].onload = function() - { - var id = this.mId; - gl.bindTexture( gl.TEXTURE_CUBE_MAP, texture.globject ); - gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false ); - gl.texImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + id, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image[id] ); - gl.bindTexture( gl.TEXTURE_CUBE_MAP, null ); - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, texture.image[0], true, true, 0, -1.0 ); - } - - texture.image[i].src = url.mSrc.replace( "_0.", "_" + i + "." ); - } - } - else if( url.mType=="webcam" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = null; - texture.loaded = false; - - texture.video = document.createElement('video'); - texture.video.width = 320; - texture.video.height = 240; - texture.video.autoplay = true; - texture.video.loop = true; - texture.video.paused = true; - - navigator.getUserMedia( { "video": true, "audio": false }, - function(stream) - { - texture.video.src = window.URL.createObjectURL(stream); - - texture.globject = gl.createTexture(); - try - { - createGLTextureLinear( gl, texture.video, texture.globject ); - texture.loaded = true; - } - catch(e) - { - alert( 'Your browser can not transfer webcam data to the GPU.'); - } - }, - function(error) - { - alert( 'Unable to capture WebCam. Please reload the page.' ); - } ); - } - else if( url.mType=="video" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = null; - texture.loaded = false; - texture.video = document.createElement('video'); - texture.video.width = 256; - texture.video.height = 256; - texture.video.loop = true; - texture.video.paused = true;//this.mForcePaused; - texture.video.mPaused = true;//this.mForcePaused; - texture.video.mMuted = this.mForceMuted; - texture.video.muted = this.mForceMuted; - if( this.mForceMuted==true ) - texture.video.volume = 0; - texture.video.autoplay = false; - texture.video.hasFalled = false; - - texture.video.addEventListener( "canplay", function(e) - { - texture.video.play(); - texture.video.paused = false; - texture.video.mPaused = false; - - texture.globject = gl.createTexture(); - createGLTextureLinear( gl, texture.video, texture.globject ); - texture.loaded = true; - - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, texture.video, true, true, 1, -1.0 ); - - } ); - - texture.video.addEventListener( "error", function(e) - { - if( texture.video.hasFalled==true ) { alert("Error: cannot load video" ); return; } - var str = texture.video.src; - str = str.substr(0,str.lastIndexOf('.') ) + ".mp4"; - texture.video.src = str; - texture.video.hasFalled = true; - } ); - - - texture.video.src = url.mSrc; - } - else if( url.mType=="music" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = null; - texture.loaded = false; - texture.audio = document.createElement('audio'); - texture.audio.loop = true; - texture.audio.mMuted = this.mForceMuted; - texture.audio.mForceMuted = this.mForceMuted; - - texture.audio.muted = this.mForceMuted; - if( this.mForceMuted==true ) - texture.audio.volume = 0; - texture.audio.autoplay = true; - texture.audio.hasFalled = false; - texture.audio.paused = true; - texture.audio.mPaused = true; - texture.audio.mSound = {}; - - if( this.mForceMuted ) - { - texture.globject = gl.createTexture(); - createAudioTexture( gl, texture.globject ); - var num = 512; - texture.audio.mSound.mFreqData = new Uint8Array( num ); - texture.audio.mSound.mWaveData = new Uint8Array( num ); - texture.loaded = true; - texture.audio.paused = false; - texture.audio.mPaused = false; - } - - texture.audio.addEventListener( "canplay", function() - { - if( this.mForceMuted ) return; - - texture.globject = gl.createTexture(); - createAudioTexture( gl, texture.globject ); - - if( me.mAudioContext != null ) - { - var ctx = me.mAudioContext; - texture.audio.mSound.mSource = ctx.createMediaElementSource( texture.audio ); - texture.audio.mSound.mAnalyser = ctx.createAnalyser(); - texture.audio.mSound.mGain = ctx.createGain(); - - texture.audio.mSound.mSource.connect( texture.audio.mSound.mAnalyser ); - texture.audio.mSound.mAnalyser.connect( texture.audio.mSound.mGain ); - texture.audio.mSound.mGain.connect( ctx.destination ); - - texture.audio.mSound.mFreqData = new Uint8Array( texture.audio.mSound.mAnalyser.frequencyBinCount ); - texture.audio.mSound.mWaveData = new Uint8Array( texture.audio.mSound.mAnalyser.frequencyBinCount ); - - texture.loaded = true; - texture.audio.paused = false; - texture.audio.mPaused = false; - } - else - { - if( me.mNoAudioMessageShowed==false ) - { - var ve = document.getElementById( "centerScreen" ); - doAlert( getCoords(ve), {mX:420,mY:160}, "Error", "Your browser does not support WebAudio.

This shader will not work as the author intended. Please consider using a WebAudio-friendly browser (Chrome).", false, null ); - me.mNoAudioMessageShowed = true; - } - } - } ); - - texture.audio.addEventListener( "error", function(e) - { - if( this.mForceMuted ) return; - - if( texture.audio.hasFalled==true ) { /*alert("Error: cannot load music" ); */return; } - var str = texture.audio.src; - str = str.substr(0,str.lastIndexOf('.') ) + ".ogg"; - texture.audio.src = str; - texture.audio.hasFalled = true; - } ); - - if( !this.mForceMuted ) - { - texture.audio.src = url.mSrc; - } - - - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, null, false, true, 2, -1.0 ); - } - else if( url.mType=="keyboard" ) - { - texture = {}; - texture.mInfo = url; - texture.globject = gl.createTexture(); - texture.loaded = true; - - texture.keyboard = {}; - - texture.keyboard.mImage = new Image(); - texture.keyboard.mImage.onload = function() - { - texture.loaded = true; - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, {mImage:texture.keyboard.mImage,mData:texture.keyboard.mData}, false, false, 4, -1.0 ); - } - texture.keyboard.mImage.src = "/img/keyboard.png"; - - - texture.keyboard.mNewTextureReady = true; - texture.keyboard.mData = new Uint8Array( 256*2 ); - - createKeyboardTexture( gl, texture.globject ); - - for( var j=0; j<(256*2); j++ ) - { - texture.keyboard.mData[j] = 0; - } - - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( me.mTextureCallbackObj, slot, {mImage:texture.keyboard.mImage,mData:texture.keyboard.mData}, false, false, 4, -1.0 ); - } - else if( url.mType==null ) - { - if( me.mTextureCallbackFun!=null ) - me.mTextureCallbackFun( this.mTextureCallbackObj, slot, null, false, true, 0, -1.0 ); - } - else - { - alert( "texture type error" ); - return; - } - - this.DestroyInput( slot ); - this.mInputs[slot] = texture; - - this.MakeHeader(); -} - -Effect.prototype.SetKeyDown = function( k ) -{ - for( var i=0; i1 ) - { - return { mFailed : true, mError : "ShaderToy only supports one-pass shaders at this momment", mShader:null }; - } - for( var j=0; j x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);", - "vec4 x12 = x0.xyxy + C.xxzz;", - "x12.xy -= i1;", - - "i = mod289(i); // Avoid truncation effects in permutation", - "vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))", - "+ i.x + vec3(0.0, i1.x, 1.0 ));", - - "vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);", - "m = m*m ;", - "m = m*m ;", - - "vec3 x = 2.0 * fract(p * C.www) - 1.0;", - "vec3 h = abs(x) - 0.5;", - "vec3 ox = floor(x + 0.5);", - "vec3 a0 = x - ox;", - - "m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );", - - "vec3 g;", - "g.x = a0.x * x0.x + h.x * x0.y;", - "g.yz = a0.yz * x12.xz + h.yz * x12.yw;", - - "return 130.0 * dot(m, g);", - "}", - - "float fbm(vec2 p) {", - "float f = 0.0;", - "float w = 0.5;", - "for (int i = 0; i < 5; i ++) {", - "f += w * snoise(p);", - "p *= 2.;", - "w *= 0.5;", - "}", - "return f;", - "}", - - - "vec4 tunneliter(vec2 texCoord,vec4 incol,float cx,float cy,float limita,float limitb,vec4 coloz,float tadd)", - "{", - "vec2 texc;", - "vec2 tex;", - "vec4 outCol;", - "float disty;", - - "texc=(texCoord-vec2(cx,cy));", - "disty=distance(texc,vec2(0.0,0.0));", - "tex.x=(abs(atan(texc.x,texc.y)))/6.2830;", - "tex.y=0.5/disty;", - "tex.y+=(iGlobalTime*0.9)+tadd;", - - "float fbmval=abs(fbm(tex));", - - "float bex=mix(fbmval,1.0,smoothstep(limitb,limita,disty))*smoothstep(limitb,limita,disty);", - "outCol=mix(incol,coloz*(1.0-fbmval),bex);", - - "return outCol;", - "}", - - "void main(void)", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.xy;", - "gl_FragColor = vec4(uv,0.5+0.5*sin(iGlobalTime),1.0);", - - "vec4 finalCol;", - - "float xa=(sin(iGlobalTime)*0.4)+(sin((iGlobalTime*1.3)+0.5)*0.24);", - "float ya=(cos(iGlobalTime)*0.45)+(cos((iGlobalTime*0.6)-0.7)*0.3);", - - "finalCol=vec4(1.0,0.0,1.0,1.0);", - - "finalCol=tunneliter(uv,vec4(1.0,1.0,1.0,1.0),0.5+(xa*0.80),0.5+(ya*0.80),0.04,0.01,vec4(0.9,0.9,1.0,1.0),3.1);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.90),0.5+(ya*0.70),0.08,0.03,vec4(0.7,0.7,0.8,1.0),7.2);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.70),0.5+(ya*0.70),0.14,0.05,vec4(0.6,0.6,0.7,1.0),9.3);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.58),0.5+(ya*0.58),0.18,0.10,vec4(0.5,0.5,0.6,1.0),4.4);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.35),0.5+(ya*0.35),0.24,0.15,vec4(0.4,0.4,0.5,1.0),2.5);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.22),0.5+(ya*0.22),0.30,0.20,vec4(0.4,0.4,0.5,1.0),9.6);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.15),0.5+(ya*0.15),0.40,0.25,vec4(0.3,0.3,0.4,1.0),6.7);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.12),0.5+(ya*0.12),0.50,0.35,vec4(0.3,0.3,0.4,1.0),3.8);", - "finalCol=tunneliter(uv,finalCol,0.5+(xa*0.10),0.5+(ya*0.10),0.60,0.40,vec4(0.3,0.3,0.4,1.0),7.9);", - - "gl_FragColor = vec4(vec3(finalCol.xyz),1.0);", - - "}"]; - -} - -PIXI.SoftTunnelFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.SoftTunnelFilter.prototype.constructor = PIXI.SoftTunnelFilter; - -Object.defineProperty(PIXI.SoftTunnelFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex15.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.SoftTunnelFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/spaceRacingLiteFilter.js b/examples/wip/filters/spaceRacingLiteFilter.js deleted file mode 100644 index 820aca668..000000000 --- a/examples/wip/filters/spaceRacingLiteFilter.js +++ /dev/null @@ -1,713 +0,0 @@ -PIXI.SpaceRacingLiteFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iMouse: { type: 'f3', value: { x: 0, y: 0, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates }, - iChannel1: { type: 'sampler2D', value: texture, wrap: 'repeat' } - }; - - // Shader by Kali (https://www.shadertoy.com/view/XsBGzw) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel1;", - "// add any extra uniforms here", - - "// Space Racing Lite", - - "// Distance function and initial design for space car is by eiffie:", - "// https://www.shadertoy.com/view/ldjGRh", - "// the rest is by me but he also helped to optimize the code.", - - "// I removed some features by default because the original was crashing the Shadertoy browser", - "// for win7 users - try commenting this lines to see if the full version compiles for you:", - - "#define LOW_QUALITY // No reflections, no shadows, no planet, reduced ray steps & detail", - "#define NO_HUD", - - "//#define LOOP_BREAKS // Could speed up, speed down, or just make your browser crash!", - - - - "#ifdef LOW_QUALITY", - "#define RAY_STEPS 65", - "#define SHADOW_STEPS 0", - "#define ITERATIONS 5", - "#define MAX_DIST 30.", - "#else", - "#define RAY_STEPS 75", - "#define SHADOW_STEPS 40", - "#define ITERATIONS 6", - "#define MAX_DIST 35.", - "#endif", - "#define LIGHT_COLOR vec3(1.,.85,.6)", - "#define AMBIENT_COLOR vec3(.7,.85,1.)", - "#define SUN_COLOR vec3(1.,.8,.5)", - "#define TUBE_COLOR vec3(1.,.6,.25)*1.2", - "#define CAR_COLOR vec3(.4,.7,1.)", - "#define TURBINES_COLOR vec3(.6,.75,1.)", - "#define HUD_COLOR vec3(0.6,1.,0.3)", - "#define PLANET_COLOR vec3(101., 153., 189.)/256.", - - "#define CAR_SCALE 4.", - "#define SPECULAR 0.4", - "#define DIFFUSE 2.0", - "#define AMBIENT 0.4", - - "#define BRIGHTNESS .9", - "#define GAMMA 1.1", - "#define SATURATION .85", - - - "#define DETAIL .004", - "#define SPEED 8.", - "#define t (mod(iGlobalTime,500.)+10.)*SPEED", - - "#define LIGHTDIR normalize(vec3(0.6,-0.2,-1.))", - - "// ------------------------------------------------------------------", - "// Global Variables", - "// ------------------------------------------------------------------", - - "float FOLD=2.; // controls fractal fold and track width", - "const vec3 planetpos=vec3(-3.5,1.,-5.); // planet position", - "const vec2 tubepos=vec2(0.35,0.); // light tubes pos relative to FOLD", - "mat2 trmx;//the turbine spinner", - "float det=0.; // detail level (varies with distance)", - "float backcam; // back cam flag", - "vec3 carpos; // car position", - "vec3 carvec; // car pointing vector", - "mat3 carrot; // car rotation", - "float hitcar; // ray-car hit flag", - "mat2 fractrot; // rot mat for fractal (set in main)", - "mat2 cartilt; // secondary car rotation", - "float minT, minL; // min distance traps for glows of tube and turbines", - "float ref; // reflection flag", - "float tubeinterval; // tube tiling (for glow and lighting)", - - - "// ------------------------------------------------------------------", - "// General functions", - "// ------------------------------------------------------------------", - - "mat2 rot(float a) {", - "return mat2(cos(a),sin(a),-sin(a),cos(a));", - "}", - - "mat3 lookat(vec3 fw,vec3 up){", - "fw=normalize(fw);vec3 rt=normalize(cross(fw,normalize(up)));return mat3(rt,cross(rt,fw),fw);", - "}", - - "float smin(float a,float b,float k){return -log(exp(-k*a)+exp(-k*b))/k;}//from iq", - - "float Sphere(vec3 p, vec3 rd, float r){", - "float b = dot( -p, rd );", - "float inner = b * b - dot( p, p ) + r * r;", - "if( inner < 0.0 ) return -1.0;", - "return b - sqrt( abs(inner) );", - "}", - - - "// ------------------------------------------------------------------", - "// Track", - "// ------------------------------------------------------------------", - - "// the track function, just some curves", - "vec3 path(float ti) {", - "float freq=.5, amp=1.; // for trying different settings", - "ti*=freq;", - "float x=cos(cos(ti*.35682)+ti*.2823)*cos(ti*.1322)*1.5;", - "float y=sin(ti*.166453)*4.+cos(cos(ti*.125465)+ti*.17354)*cos(ti*.05123)*2.;", - "vec3 p=vec3(x,y,ti/freq);", - "return p;", - "}", - - "// see if we are in the tunnel, and used also by distance function", - "float tunnel(float z) {", - "return abs(100.-mod(z+15.,200.))-30.;", - "}", - - - "// ------------------------------------------------------------------", - "// DE functions", - "// ------------------------------------------------------------------", - - - "// carcarspacecar by eiffie // (with some mods by Kali)", - "// a reconfig of the carcar's tires (someday I will have to do an animation from the original to this)", - "//the DE looks a bit long but there are actually fewer instructions than the car", - - "float carcarDE(in vec3 p0){", - "p0.xy*=cartilt;", - "p0*=CAR_SCALE;", - "vec3 p=p0;", - "p.y+=1.24;", - "float r=length(p.yz);", - "float d=length(max(vec3(abs(p.x)-0.35,r-1.92,-p.y+1.4),0.0))-0.05;", - "d=max(d,p.z-1.05);", - "p=p0+vec3(0.0,-0.22,0.39);", - "p.xz=abs(p.xz);", - "p.xyz-=vec3(0.72,0.0,1.06);", - "float w1=0.23,w2=0.24;", - "if(p0.z<0.0){//this is discontinuous yet works unless you stand in front of the rear turbines", - "w1=0.23,w2=0.05; //where you would get sucked into the blades anyways", - "p=p.xzy; //so i'm comfortable with it :)", - "}", - "r=length(p.xy);", - "d=smin(d,length(vec2(max(abs(p.z)-w2,0.0),r-w1))-0.02,8.0);//done with the car shape, the rest is just turbines and could be replaced with lights or something", - "d=min(d,(length(p*vec3(1.,1.,.6))-.08-p0.z*.03));", - "p.xy=trmx*p.xy;//spin", - "float d2=min(abs(p.x),abs(p.y))*.15;//4 blades", - "//p.xy=mat2(0.707,-0.707,0.707,0.707)*p.xy;//45 degree turn", - "//d2=min(d2,min(abs(p.x),abs(p.y))*.2);//8 blades", - "d2=max(r-w1-.05,max(d2-0.005,abs(p.z)-w2+0.04));", - "d2=min(d2,(length(p)-.05-p0.z*.035)*.07);", - "d2=min(d2,max(d+.02,max(abs(p0.y-.07),abs(p0.x)-.4+min(0.,p0.z)))*.18);", - "minL=min(minL,d2);//catch the minimum distance to the glowing parts", - "// I used d2 only for glows (Kali)", - "return d/CAR_SCALE;// *carScale", - "}", - - - "vec3 carcarCE(in vec3 p0){//coloring", - "p0*=CAR_SCALE;", - "vec4 trpc=vec4(0.);//color trap (taking samples when finding the norm)// not for now (Kali)", - - "//right here you should inv-transform p0 as it gets used later", - "//p0=(p0-carPos)*carRot/carScale;//or something like that??", - "p0.xy*=cartilt;", - "vec3 p=p0;", - "p.y+=1.24;", - "float r=length(p.yz);", - "float d=length(max(vec3(abs(p.x)-0.35,r-1.92,-p.y+1.4),0.0))-0.05;", - "d=max(d,p.z-1.0);", - "p=p0+vec3(0.0,-0.22,0.39);", - "p.xz=abs(p.xz);", - "p.xyz-=vec3(0.72,0.0,1.06);", - "float w1=0.2,w2=0.24;", - "if(p0.z<0.0){//this is discontinuous yet works unless you stand in front of the rear turbines", - "w1=0.23,w2=0.05; //where you would get sucked into the blades anyways", - "p=p.xzy; //so i'm comfortable with it :)", - "}", - "r=length(p.xy);", - "d=smin(d,length(vec2(max(abs(p.z)-w2,0.0),r-w1))-0.02,8.0);//done with the car shape, the rest is just turbines and could be replaced with lights or something", - "p.xy=trmx*p.xy;", - "float d2=min(abs(p.x),abs(p.y));//4 blades", - "p.xy=mat2(0.707,-0.707,0.707,0.707)*p.xy;//45 degrees", - "d2=min(d2,min(abs(p.x),abs(p.y)));//8 blades", - "d2=max(r-w1+0.02,max(d2-0.005,abs(p.z)-w2+0.04));", - "//up to here it is the same as DE, now accumulate colors", - "if(d20.05-p0.z*0.09 || p0.z>0.25) &&", - "length(max(abs(p0.xz+vec2(-p0.z*.03,-0.5))-vec2(0.15+p0.z*.03,0.4),0.0))>0.1)", - "trpc+=vec4(CAR_COLOR,16.0);", - "else trpc+=vec4(CAR_COLOR*.4,2.0);//the windsheild", - "}", - "return trpc.xyz; // *carScale", - "}", - - "//-------------------------------------------", - - "// DE for tubes", - "float tubes(vec3 pos) {", - "pos.x=abs(pos.x)-tubepos.x-FOLD;", - "pos.y+=tubepos.y;", - "return (length(pos.xy)-.05);", - "}", - - "// ------------------------------------------------------------------", - "// SCENE DE", - "// ------------------------------------------------------------------", - - "float de(vec3 pos) {", - "vec3 carp=pos-carpos; // scale car coordinates", - "carp=carrot*carp; // rotate car", - "pos.xy-=path(pos.z).xy; // transform coordinates to follow track", - "FOLD=1.7+pow(abs(100.-mod(pos.z,200.))/100.,2.)*2.; //varies fractal fold & track width", - "pos.x-=FOLD;", - "float hid=0.;", - "vec3 tpos=pos;", - "tpos.z=abs(2.-mod(tpos.z,4.));", - "vec4 p=vec4(tpos,1.);", - "for (int i=0; iDETAIL) {", - "vec3 p = pos - totdist * sdir;", - "dist = de(p);", - "sh = min(sh, 10.*max(0.0,dist)/totdist);", - "sh*= sign(max(0.,dist-DETAIL));", - "totdist += max(0.02,dist);", - "}", - "#ifdef LOOP_BREAKS", - "else break;", - "#endif", - "}", - - "return clamp(sh,0.,1.0);", - "}", - - "#endif", - - "float calcAO(vec3 pos, vec3 nor) {", - "float hr,dd,aoi=0.,sca=1.,totao=0.;", - "hr = .075*aoi*aoi;dd = de(nor * hr + pos);totao += (hr-dd)*sca;sca*=.6;aoi++;", - "hr = .075*aoi*aoi;dd = de(nor * hr + pos);totao += (hr-dd)*sca;sca*=.55;aoi++;", - "hr = .075*aoi*aoi;dd = de(nor * hr + pos);totao += (hr-dd)*sca;sca*=.55;aoi++;", - "hr = .075*aoi*aoi;dd = de(nor * hr + pos);totao += (hr-dd)*sca;sca*=.55;aoi++;", - "return clamp( 1.0 - 4.*totao, 0., 1.0 );", - "}", - - - "// ------------------------------------------------------------------", - "// Light and Coloring", - "// ------------------------------------------------------------------", - - - - "vec3 shade(in vec3 p, in vec3 dir, in vec3 n) {", - - "float savehitcar=hitcar;", - - "vec3 trackoffset=-vec3(path(p.z).xy,0.);", - "vec3 pos=p;", - "vec3 col=vec3(.5); // main color", - "vec3 carp=pos-carpos; //scaled coordinates for the car", - "carp=carrot*carp; // rotate car", - "pos+=trackoffset; // apply track transformation to the coordinates", - "// track lines", - "if (pos.y<.5) col+=pow(max(0.,.2-abs(pos.x))/.2*abs(sin(pos.z*2.)),8.)*TUBE_COLOR*2.;", - "pos.x=abs(pos.x);", - "// fake AO for the tunnel's upper corners", - "if(tunnel(pos.z)<0.)", - "col*=1.-pow(max(0.5,1.-length(pos.xy+vec2(-FOLD*1.5,-.85))),5.)*max(0.,1.+pos.y);", - "if (tubes(pos)0.) {", - "falloff1=pow(max(0.,1.-.15*distance(vec3(p.xy,0.),vec3(-tpos1.xy,0.))),4.);", - "falloff2=pow(max(0.,1.-.15*distance(vec3(p.xy,0.),vec3(-tpos2.xy,0.))),4.);", - "} else {", - "falloff1=pow(max(0.,1.-.2*distance(vec3(p.xy,0.),vec3(-tpos1.xy,0.))),4.);", - "falloff2=pow(max(0.,1.-.2*distance(vec3(p.xy,0.),vec3(-tpos2.xy,0.))),4.);", - "}", - - "float diff, spec;", - - "vec3 r=reflect(LIGHTDIR,n);", - - "// tube1 calcs", - "diff=max(0.,dot(tube1lightdir,-n));", - "diff+=max(0.,dot(normalize(tube1lightdir+vec3(0.,0.,.2)),-n))*.5; // add 2 more", - "diff+=max(0.,dot(normalize(tube1lightdir-vec3(0.,0.,.2)),-n))*.5; // with Z shifted", - "spec=pow(max(0.,dot(tube1lightdir+vec3(0.,0.,.4),r)),15.)*.7;", - "spec+=pow(max(0.,dot(tube1lightdir-vec3(0.,0.,.4),r)),15.)*.7;", - "float tl1=(falloff1*ao+diff+spec)*falloff1;", - - "// tube2 calcs", - "diff=max(0.,dot(tube2lightdir,-n));", - "diff+=max(0.,dot(normalize(tube2lightdir+vec3(0.,0.,.2)),-n))*.5;", - "diff+=max(0.,dot(normalize(tube2lightdir-vec3(0.,0.,.2)),-n))*.5;", - "spec=pow(max(0.,dot(tube2lightdir+vec3(0.,0.,.4),r)),15.)*.7;", - "spec+=pow(max(0.,dot(tube2lightdir-vec3(0.,0.,.4),r)),15.)*.7;", - "float tl2=(falloff2*ao+diff+spec)*falloff2;", - - "// sum tube lights - add ambient - apply tube intervall", - "vec3 tl=((tl1+tl2)*(.5+tubeinterval*.5))*TUBE_COLOR;//*(1.+tun*.5);", - - - "// --- Car lights ---", - - "// get the car turbines direction (aproximate)", - "vec3 carlightdir1=normalize(p-carpos+vec3(.2,0.06,.15));", - "vec3 carlightdir2=normalize(p-carpos+vec3(-.2,0.06,.15));", - "vec3 carlightdir3=normalize(p-carpos+vec3(.2,0.06,-.35));", - "vec3 carlightdir4=normalize(p-carpos+vec3(-.2,0.06,-.35));", - - "float cfalloff=pow(max(0.,1.-.1*distance(p,carpos)),13.); // car light falloff", - - "// accumulate diffuse", - "diff=max(0.,dot(carlightdir1,-n))*.5;", - "diff+=max(0.,dot(carlightdir2,-n))*.5;", - "diff+=max(0.,dot(carlightdir3,-n))*.5;", - "diff+=max(0.,dot(carlightdir4,-n))*.5;", - - "if (savehitcar<1.) diff*=clamp(1.-carlightdir1.y,0.,1.);", - - "// add ambient and save car lighting", - "vec3 cl=TURBINES_COLOR*((diff+spec*.0)*cfalloff+cfalloff*.3)*1.2;", - - "// --- Main light ---", - - "#ifdef LOW_QUALITY", - "float sh=ao;", - "#else", - "float sh=shadow(p, LIGHTDIR); // get shadow", - "#endif", - - "diff=max(0.,dot(LIGHTDIR,-n))*sh*1.3; // diffuse", - "float amb=(.4+.6*camlight)*.6; // ambient+camlight", - "spec=pow(max(0.,dot(dir,-r))*sh,20.)*SPECULAR; //specular", - "if (savehitcar>0.) {diff*=.8;amb*=.3;}", - "vec3 l=(amb*ao*AMBIENT_COLOR+diff*LIGHT_COLOR)+spec*LIGHT_COLOR;", - - "if (col==TUBE_COLOR) l=.3+vec3(camlight)*.7; // special lighting for tubes", - - "return col*(l+cl+tl); // apply all lights to the color", - "}", - - "// the planet shading...", - "// very simple and fast made, but for low res windowed mode it does the job :)", - "vec3 shadeplanet(vec3 pos, vec3 k) {", - - "vec3 n=normalize(planetpos+pos+.2); // tweaked sphere normal", - "float c=max(0.,dot(LIGHTDIR,normalize(k-n))); // surface value", - "vec3 col=PLANET_COLOR+vec3(c,c*c,c*c*c)*.7; // surface coloring", - "// add some noise", - "float noi=max(0.,texture2D(iChannel1,n.yz*.5).x-.6);", - "noi+=max(0.,texture2D(iChannel1,n.yz).x-.6);", - "noi+=max(0.,texture2D(iChannel1,n.yz*2.).x-.6);", - "col+=noi*(1.5-c)*.7;", - "return col*max(0.,dot(LIGHTDIR,-n)); // diff light", - "}", - - "// ------------------------------------------------------------------", - "// Raymarching + FX rendering", - "// ------------------------------------------------------------------", - - - "vec3 raymarch(in vec3 from, in vec3 dir)", - - "{", - "hitcar=0.;", - "ref=0.;", - "float totdist=0.;", - "float glow=0.;", - "float d=1000.;", - "vec3 p=from, col=vec3(0.5);", - - "float deta=DETAIL*(1.+backcam); // lower detail for HUD cam", - "vec3 carp=vec3(0.); // coordinates for car hit", - "vec3 carn=vec3(0.); // normal for car", - "float cardist=0.; // ray length for car", - "vec3 odir=dir; // save original ray direction", - - "for (int i=0; idet && totdist0. && ref<1.) { // hit car, bounce ray (only once)", - "p=p-abs(d-det)*dir; // backstep", - "carn=normal(p); // save car normal", - "carp=p; // save car hit pos", - "dir=reflect(dir,carn); // reflect ray", - "p+=det*dir*10.; // advance ray", - "d=10.; cardist=totdist;", - "ref=1.;", - "}", - "#endif", - "}", - "#ifdef LOOP_BREAKS", - "else break;", - "#endif", - "}", - - "tubeinterval=abs(1.+cos(p.z*3.14159*.5))*.5; // set light tubes interval", - "float cglow=1./(1.0+minL*minL*5000.0); // car glow", - "float tglow=1./(1.0+minT*minT*5000.0); // tubes glow", - "float l=max(0.,dot(normalize(-dir),normalize(LIGHTDIR))); // lightdir gradient", - "vec3 backg=AMBIENT_COLOR*.4*max(0.1,pow(l,5.)); // background", - "float lglow=pow(l,50.)*.5+pow(l,200.)*.5; // sun glow", - - "if (d<.5) { // hit surface", - "vec3 norm=normal(p); // get normal", - "p=p-abs(d-det)*dir; // backstep", - "col=shade(p, dir, norm); // get shading", - "col+=tglow*TUBE_COLOR*pow(tubeinterval,1.5)*2.; // add tube glow", - "col = mix(backg, col, exp(-.015*pow(abs(totdist),1.5))); // distance fading", - - "} else { // hit background", - "col=backg; // set color to background", - "col+=lglow*SUN_COLOR; // add sun glow", - "col+=glow*pow(l,5.)*.035*LIGHT_COLOR; // borders glow", - - "#ifdef LOW_QUALITY", - "vec3 st = (dir * 3.+ vec3(1.3,2.5,1.25)) * .3;", - "for (int i = 0; i < 14; i++) st = abs(st) / dot(st,st) - .9;", - - "col+= min( 1., pow( min( 5., length(st) ), 3. ) * .0025 ); // add stars", - "#else", - "float planet=Sphere(planetpos,dir, 2.); // raytrace planet", - - "// kaliset formula - used for stars and planet surface", - "float c;", - "if (planet>0.) c=1.; else c=.9; // different params for planet and stars", - "vec3 st = (dir * 3.+ vec3(1.3,2.5,1.25)) * .3;", - "for (int i = 0; i < 14; i++) st = abs(st) / dot(st,st) - c;", - - "col+= min( 1., pow( min( 5., length(st) ), 3. ) * .0025 ); // add stars", - - "// planet atmosphere", - "col+=PLANET_COLOR*pow(max(0.,dot(dir,normalize(-planetpos))),100.)*150.*(1.-dir.x);", - "// planet shading", - "if (planet>0.) col=shadeplanet(planet*dir,st);", - "#endif", - - "}", - "// car shading", - - "// add turbine glows", - - "#ifdef LOW_QUALITY", - "cglow*=1.15;", - "#else", - "if (ref>0.) {", - "ref=0.;", - "col=shade(carp,odir,carn)+col*.3; // car shade + reflection", - "// I wanted a lighter background for backward reflection", - "l=max(0.,dot(normalize(-odir),normalize(LIGHTDIR)));", - "backg=AMBIENT_COLOR*.4*max(0.1,pow(l,5.));", - "col = mix(backg, col,exp(-.015*pow(abs(cardist),1.5))); // distance fading", - "}", - "#endif", - - - "col+=TURBINES_COLOR*pow(abs(cglow),2.)*.4;", - "col+=TURBINES_COLOR*cglow*.15;", - - - "return col;", - "}", - - "// simple HUD track graph with transparency", - "vec4 showtrack(vec2 p) {", - "p.x+=.25;", - "vec2 uv=p;", - "float uvpos=uv.x+1.5;", - "vec3 pth=path((uvpos-1.5)*30.+t)*.05;", - "float curpos=path(t).x*.05;", - "float curs=pow(max(0.,1.-length(uv+vec2(0.,curpos))*2.),10.)*max(0.5,sin(iGlobalTime*10.))*2.;", - "uv.xy=uv.xy-(vec2(uvpos,0.))*rot(pth.x/uvpos);", - "float dotline=pow(max(0.,1.-abs(uv.y)*5.),30.);", - "float graph=(curs+dotline);", - "return vec4((graph+.4)*HUD_COLOR,1.-.5*pow(abs(.025-mod(p.y*2.,.05))/.025,2.));", - "}", - - - "// ------------------------------------------------------------------", - "// Main code - Camera - HUD", - "// ------------------------------------------------------------------", - - - "void main(void)", - "{", - "minL=minT=1000.; // initialize min distance glows", - "fractrot=rot(.5); // mat2D for the fractal formula", - "vec3 carpos0=vec3(0.,-0.2,.0); // set relative car pos (unused now, only sets height)", - "carpos=vec3(carpos0+vec3(0.,0.,t)); // real car pos", - "vec3 carmove=path(carpos.z); carmove.x*=1.+FOLD*.1; // get pos, exagerate x pos based on track width.", - "carvec=normalize((path(carpos.z+2.)-carmove)*vec3(FOLD*.25,1.,1.)); // car fwd vector", - "carrot=lookat(-carvec,vec3(0.,1.,0.)); // car rotation", - "cartilt=rot(-carvec.x*2.); // xy rotation based on distance from center", - "carpos.xy+=carmove.xy-vec2(carvec.x,0.)*FOLD*.5; // move away from center when turning", - "float tim=iGlobalTime*12.0;", - "trmx=mat2(cos(tim),-sin(tim),sin(tim),cos(tim));//the turbine spinner", - - "// --- camera & mouse ---", - - "vec2 uv = gl_FragCoord.xy / iResolution.xy*2.-1.;", - "uv.y*=iResolution.y/iResolution.x;", - "vec2 mouse=(iMouse.xy/iResolution.xy-.5)*vec2(7.,1.5);", - "if (iMouse.z<1.) { // if no mouse, alternate rear and back cam", - "mouse=vec2(sin(iGlobalTime)*.7,2.+sin(iGlobalTime*.2)*.22)", - "*min(0.,sign(10.-mod(iGlobalTime,20.)));", - "}", - "vec3 dir=normalize(vec3(uv*.8,1.));", - - "vec3 campos=vec3(0.,0.2,-.6); // original relative camera position", - "//rotate camera with mouse", - "campos.yz=(campos.yz-carpos0.yz)*rot(mouse.y)+carpos0.yz;", - "campos.xz=(campos.xz-carpos0.xz)*rot(mouse.x)+carpos0.xz;", - "campos.x-=carvec.x*FOLD; // follow car x pos a bit when turning", - - "vec3 from;", - - "float fixcam=5.;", - "float mt=mod(t/SPEED,fixcam*2.);", - "//fixed cam every 15 seconds, random position, point at car position", - "if ((mod(iGlobalTime,20.)>15. && iMouse.z<1.)) {", - "fixcam*=SPEED;", - "from=path(floor(t/fixcam)*fixcam+fixcam*.5);", - "//from.x+=1.; from.y+=.5;", - "vec2 fixpos=(texture2D(iChannel1,vec2(from.z*.21325)).xy-.5)*vec2(FOLD*2.-.3,1.);", - "fixpos.x+=sign(fixpos.x)*.3; fixpos.y+=.2;", - "from.xy+=fixpos;", - "dir=lookat(normalize(carpos-from),vec3(0.,1.,0.))*normalize(dir+vec3(0.,0.,0.5));", - - "} else { //normal cam", - "from=path(t+campos.z)+campos;", - "dir.y-=.3*campos.z;", - "dir=lookat(normalize(carpos-from),vec3(0.,1.,0.))*normalize(dir);", - "}", - - "vec4 hud=vec4(0.);", - - "#ifndef NO_HUD", - "//HUD (hud camera was going to be transparent but won't compile)", - "backcam=0.;", - "vec2 huv=uv+vec2(.75,.44);", - "if (length(huv*huv*huv*vec2(5.,50.))<.05) hud=showtrack(huv*2.); // track HUD", - "uv+=vec2(-.75,.44);", - "if (length(uv*uv*uv*vec2(5.,50.))<.05) { //set ray data for HUD cam", - "backcam=1.;", - "uv*=6.;", - "dir=normalize(vec3(uv.xy*.6,-1.));", - "from=vec3(carvec.x*.5,0.1,0.)+path(t-campos.z*1.7);", - "dir=lookat(-normalize(carpos-from),normalize(vec3(0.,1.,0.)))*dir;", - "//color+=HUD_COLOR*(vec3(HUDraymarch(from,dir))+.1);", - "}", - - "#endif", - - "vec3 color=raymarch(from,dir); // Raymarch scene", - "color=clamp(color,vec3(.0),vec3(1.));", - "if (backcam>0.) { //if HUD cam, apply post effect", - "color=(.2+pow(length(color),1.7)*.5)*HUD_COLOR", - "*(1.-.5*pow(abs(.025-mod(uv.y*.9,.05))/.025,2.))*.9;", - "}", - - "color=hud.rgb*hud.a+color*(1.-hud.a);//HUD transparency", - - "//color adjustments", - "color=pow(abs(color),vec3(GAMMA))*BRIGHTNESS;", - "color=mix(vec3(length(color)),color,SATURATION);", - "gl_FragColor = vec4(color,1.);", - "}"]; - - -} - -PIXI.SpaceRacingLiteFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.SpaceRacingLiteFilter.prototype.constructor = PIXI.SpaceRacingLiteFilter; - -Object.defineProperty(PIXI.SpaceRacingLiteFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex00.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.SpaceRacingLiteFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - filter.uniforms.iMouse.value.x = game.input.x; - filter.uniforms.iMouse.value.y = game.input.y; - -} - -function render() { -} diff --git a/examples/wip/filters/starNestFilter.js b/examples/wip/filters/starNestFilter.js deleted file mode 100644 index 05b31f844..000000000 --- a/examples/wip/filters/starNestFilter.js +++ /dev/null @@ -1,145 +0,0 @@ -PIXI.StarNestFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture } - }; - - // Shader by Kali (https://www.shadertoy.com/view/4dfGDM) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - "// Star Nest by Pablo Román Andrioli", - - "// This content is under the MIT License.", - - "#define iterations 17", - "#define formuparam 0.530", - - "#define volsteps 18", - "#define stepsize 0.100", - - "#define zoom 0.800", - "#define tile 0.850", - "#define speed 0.010", - - "#define brightness 0.0015", - "#define darkmatter 0.300", - "#define distfading 0.760", - "#define saturation 0.800", - - - "void main(void)", - "{", - "//get coords and direction", - "vec2 uv=gl_FragCoord.xy/iResolution.xy-.5;", - "uv.y*=iResolution.y/iResolution.x;", - "vec3 dir=vec3(uv*zoom,1.);", - "float time=iGlobalTime*speed+.25;", - - "//mouse rotation", - "float a1=.5+iMouse.x/iResolution.x*2.;", - "float a2=.8+iMouse.y/iResolution.y*2.;", - "mat2 rot1=mat2(cos(a1),sin(a1),-sin(a1),cos(a1));", - "mat2 rot2=mat2(cos(a2),sin(a2),-sin(a2),cos(a2));", - "dir.xz*=rot1;", - "dir.xy*=rot2;", - "vec3 from=vec3(1.,.5,0.5);", - "from+=vec3(time*2.,time,-2.);", - "from.xz*=rot1;", - "from.xy*=rot2;", - - "//volumetric rendering", - "float s=0.1,fade=1.;", - "vec3 v=vec3(0.);", - "for (int r=0; r3) fade*=1.-dm; // dark matter, don't render near", - "//v+=vec3(dm,dm*.5,0.);", - "v+=fade;", - "v+=vec3(s,s*s,s*s*s*s)*a*brightness*fade; // coloring based on distance", - "fade*=distfading; // distance fading", - "s+=stepsize;", - "}", - "v=mix(vec3(length(v)),v,saturation); //color adjust", - "gl_FragColor = vec4(v*.01,1.);", - - "}"]; - -} - -PIXI.StarNestFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.StarNestFilter.prototype.constructor = PIXI.StarNestFilter; - -Object.defineProperty(PIXI.StarNestFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'wip/tex16.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.StarNestFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/starNurseryFilter.js b/examples/wip/filters/starNurseryFilter.js deleted file mode 100644 index 5808ad81a..000000000 --- a/examples/wip/filters/starNurseryFilter.js +++ /dev/null @@ -1,235 +0,0 @@ -PIXI.StarNurseryFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, textureData: { repeat: true } } - }; - - // Shader by Dave Hoskins (https://www.shadertoy.com/view/XsfGzH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "// Built from the basics of'Clouds' Created by inigo quilez - iq/2013", - "// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.", - - "// Edited by Dave Hoskins into Star Nursery", - "// V.1.1 Some speed up in the ray-marching loop.", - "// V.1.2 Added Shadertoy's fast 3D noise for better, smaller step size.", - - "mat3 m = mat3( 0.00, 0.90, 0.60,", - "-0.90, 0.36, -0.48,", - "-0.60, -0.48, 0.34 );", - "float time = iGlobalTime+46.0;", - - "//----------------------------------------------------------------------", - "float hash( float n )", - "{", - "return fract(sin(n)*43758.5453123);", - "}", - - "//----------------------------------------------------------------------", - "float noise( in vec2 x )", - "{", - "vec2 p = floor(x);", - "vec2 f = fract(x);", - - "f = f*f*(3.0-2.0*f);", - - "float n = p.x + p.y*57.0;", - - "float res = mix(mix( hash(n+ 0.0), hash(n+ 1.0),f.x),", - "mix( hash(n+ 57.0), hash(n+ 58.0),f.x),f.y);", - - "return res;", - "}", - - "//----------------------------------------------------------------------", - "float noise( in vec3 x )", - "{", - "vec3 p = floor(x);", - "vec3 f = fract(x);", - "f = f*f*(3.0-2.0*f);", - - "vec2 uv = (p.xy+vec2(37.0,17.0)*p.z) + f.xy;", - "vec2 rg = texture2D( iChannel0, (uv+ 0.5)/256.0, -100.0 ).yx;", - "return mix( rg.x, rg.y, f.z );", - "}", - - "//----------------------------------------------------------------------", - "float fbm( vec3 p )", - "{", - "float f;", - "f = 1.600*noise( p ); p = m*p*2.02;", - "f += 0.3500*noise( p ); p = m*p*2.33;", - "f += 0.2250*noise( p ); p = m*p*2.01;", - "f += 0.0825*noise( p ); p = m*p*2.01;", - "return f;", - "}", - - "//----------------------------------------------------------------------", - "vec4 map( in vec3 p )", - "{", - "float d = 0.01- p.y;", - - "float f= fbm( p*1.0 - vec3(.4,0.3,-0.3)*time);", - "d += 4.0 * f;", - - "d = clamp( d, 0.0, 1.0 );", - - "vec4 res = vec4( d );", - "res.w = pow(res.y, .1);", - - "res.xyz = mix( .7*vec3(1.0,0.4,0.2), vec3(0.2,0.0,0.2), res.y * 1.);", - "res.xyz = res.xyz + pow(abs(.95-f), 26.0) * 1.85;", - "return res;", - "}", - - - "//----------------------------------------------------------------------", - "vec3 sundir = vec3(1.0,0.4,0.0);", - "vec4 raymarch( in vec3 ro, in vec3 rd )", - "{", - "vec4 sum = vec4(0, 0, 0, 0);", - - "float t = 0.0;", - "vec3 pos = vec3(0.0, 0.0, 0.0);", - "for(int i=0; i<100; i++)", - "{", - "if (sum.a > 0.8 || pos.y > 9.0 || pos.y < -2.0) continue;", - "pos = ro + t*rd;", - - "vec4 col = map( pos );", - - "// Accumulate the alpha with the colour...", - "col.a *= 0.08;", - "col.rgb *= col.a;", - - "sum = sum + col*(1.0 - sum.a);", - "t += max(0.1,0.04*t);", - "}", - "sum.xyz /= (0.003+sum.w);", - - "return clamp( sum, 0.0, 1.0 );", - "}", - - "//----------------------------------------------------------------------", - "void main(void)", - "{", - "vec2 q = gl_FragCoord.xy / iResolution.xy;", - "vec2 p = -1.0 + 2.0*q;", - "p.x *= iResolution.x/ iResolution.y;", - "vec2 mo = (-1.0 + 2.0 + iMouse.xy) / iResolution.xy;", - - "// Camera code...", - "vec3 ro = 5.6*normalize(vec3(cos(2.75-3.0*mo.x), .4-1.3*(mo.y-2.4), sin(2.75-2.0*mo.x)));", - "vec3 ta = vec3(.0, 5.6, 2.4);", - "vec3 ww = normalize( ta - ro);", - "vec3 uu = normalize(cross( vec3(0.0,1.0,0.0), ww ));", - "vec3 vv = normalize(cross(ww,uu));", - "vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );", - - "// Ray march into the clouds adding up colour...", - "vec4 res = raymarch( ro, rd );", - - - "float sun = clamp( dot(sundir,rd), 0.0, 2.0 );", - "vec3 col = mix(vec3(.3,0.0,0.05), vec3(0.2,0.2,0.3), sqrt(max(rd.y, 0.001)));", - "col += .4*vec3(.4,.2,0.67)*sun;", - "col = clamp(col, 0.0, 1.0);", - "col += 0.43*vec3(.4,0.4,0.2)*pow( sun, 21.0 );", - - "// Do the stars...", - "float v = 1.0/( 2. * ( 1. + rd.z ) );", - "vec2 xy = vec2(rd.y * v, rd.x * v);", - "float s = noise(rd.xz*134.);", - "s += noise(rd.xz*370.);", - "s += noise(rd.xz*870.);", - "s = pow(s,19.0) * 0.00000001 * max(rd.y, 0.0);", - "if (s > 0.0)", - "{", - "vec3 backStars = vec3((1.0-sin(xy.x*20.0+time*13.0*rd.x+xy.y*30.0))*.5*s,s, s);", - "col += backStars;", - "}", - - "// Mix in the clouds...", - "col = mix( col, res.xyz, res.w*1.3);", - - "#define CONTRAST 1.1", - "#define SATURATION 1.15", - "#define BRIGHTNESS 1.03", - "col = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), col*BRIGHTNESS)), col*BRIGHTNESS, SATURATION), CONTRAST);", - - "gl_FragColor = vec4( col, 1.0 );", - "}"]; - - - -} - -PIXI.StarNurseryFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.StarNurseryFilter.prototype.constructor = PIXI.StarNurseryFilter; - -Object.defineProperty(PIXI.StarNurseryFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'wip/tex12.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.StarNurseryFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/starfieldFilter.js b/examples/wip/filters/starfieldFilter.js deleted file mode 100644 index 9c74109f9..000000000 --- a/examples/wip/filters/starfieldFilter.js +++ /dev/null @@ -1,144 +0,0 @@ -PIXI.StarFieldFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, textureData: { repeat: true } } - }; - - // Shader by Rebb / TRSI (https://www.shadertoy.com/view/XdX3Wn) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - - "// add any extra uniforms here", - - "const float tau = 6.28318530717958647692;", - - "// Gamma correction", - "#define GAMMA (2.2)", - - "vec3 ToLinear( in vec3 col )", - "{", - "// simulate a monitor, converting colour values into light values", - "return pow( col, vec3(GAMMA) );", - "}", - - "vec3 ToGamma( in vec3 col )", - "{", - "// convert back into colour values, so the correct light will come out of the monitor", - "return pow( col, vec3(1.0/GAMMA) );", - "}", - - "vec4 Noise( in ivec2 x )", - "{", - "return texture2D( iChannel0, (vec2(x)+0.5)/256.0, -100.0 );", - "}", - - "vec4 Rand( in int x )", - "{", - "vec2 uv;", - "uv.x = (float(x)+0.5)/256.0;", - "uv.y = (floor(uv.x)+0.5)/256.0;", - "return texture2D( iChannel0, uv, -100.0 );", - "}", - - - "void main(void)", - "{", - "vec3 ray;", - "ray.xy = 2.0*(gl_FragCoord.xy-iResolution.xy*.5)/iResolution.x;", - "ray.z = 1.0;", - - "float offset = iGlobalTime*.5;", - "float speed2 = (cos(offset)+1.0)*2.0;", - "float speed = speed2+.1;", - "offset += sin(offset)*.96;", - "offset *= 2.0;", - - - "vec3 col = vec3(0);", - - "vec3 stp = ray/max(abs(ray.x),abs(ray.y));", - - "vec3 pos = 2.0*stp+.5;", - "for ( int i=0; i < 20; i++ )", - "{", - "float z = Noise(ivec2(pos.xy)).x;", - "z = fract(z-offset);", - "float d = 50.0*z-pos.z;", - "float w = pow(max(0.0,1.0-8.0*length(fract(pos.xy)-.5)),2.0);", - "vec3 c = max(vec3(0),vec3(1.0-abs(d+speed2*.5)/speed,1.0-abs(d)/speed,1.0-abs(d-speed2*.5)/speed));", - "col += 1.5*(1.0-z)*c*w;", - "pos += stp;", - "}", - - "gl_FragColor = vec4(ToGamma(col),1.0);", - "}"]; - -} - -PIXI.StarFieldFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.StarFieldFilter.prototype.constructor = PIXI.StarFieldFilter; - -Object.defineProperty(PIXI.StarFieldFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'wip/tex16.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.StarFieldFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/starsBackgroundFilter.js b/examples/wip/filters/starsBackgroundFilter.js deleted file mode 100644 index 1ea516925..000000000 --- a/examples/wip/filters/starsBackgroundFilter.js +++ /dev/null @@ -1,117 +0,0 @@ -PIXI.StarsBackgroundFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture } - }; - - // Shader by urraka (https://www.shadertoy.com/view/lsfGWH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "#define M_PI 3.1415926535897932384626433832795", - - "float rand(vec2 co)", - "{", - "return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);", - "}", - - "void main(void)", - "{", - "float size = 30.0;", - "float prob = 0.95;", - - "vec2 pos = floor(1.0 / size * gl_FragCoord.xy);", - - "float color = 0.0;", - "float starValue = rand(pos);", - - "if (starValue > prob)", - "{", - "vec2 center = size * pos + vec2(size, size) * 0.5;", - - "float t = 0.9 + 0.2 * sin(iGlobalTime + (starValue - prob) / (1.0 - prob) * 45.0);", - - "color = 1.0 - distance(gl_FragCoord.xy, center) / (0.5 * size);", - "color = color * t / (abs(gl_FragCoord.y - center.y)) * t / (abs(gl_FragCoord.x - center.x));", - "}", - "else if (rand(gl_FragCoord.xy / iResolution.xy) > 0.996)", - "{", - "float r = rand(gl_FragCoord.xy);", - "color = r * (0.25 * sin(iGlobalTime * (r * 5.0) + 720.0 * r) + 0.75);", - "}", - - "gl_FragColor = vec4(vec3(color), 1.0);", - "}"]; - - - -} - -PIXI.StarsBackgroundFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.StarsBackgroundFilter.prototype.constructor = PIXI.StarsBackgroundFilter; - -Object.defineProperty(PIXI.StarsBackgroundFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.image('texture', 'wip/64x64.png'); - game.load.image('texture', 'wip/tex08.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.StarsBackgroundFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/tex00.jpg b/examples/wip/filters/tex00.jpg deleted file mode 100644 index a27ca5c78..000000000 Binary files a/examples/wip/filters/tex00.jpg and /dev/null differ diff --git a/examples/wip/filters/tex01.jpg b/examples/wip/filters/tex01.jpg deleted file mode 100644 index 482f41b3f..000000000 Binary files a/examples/wip/filters/tex01.jpg and /dev/null differ diff --git a/examples/wip/filters/tex02.jpg b/examples/wip/filters/tex02.jpg deleted file mode 100644 index 748625279..000000000 Binary files a/examples/wip/filters/tex02.jpg and /dev/null differ diff --git a/examples/wip/filters/tex03.jpg b/examples/wip/filters/tex03.jpg deleted file mode 100644 index fe64a0f08..000000000 Binary files a/examples/wip/filters/tex03.jpg and /dev/null differ diff --git a/examples/wip/filters/tex04.jpg b/examples/wip/filters/tex04.jpg deleted file mode 100644 index af866a0f7..000000000 Binary files a/examples/wip/filters/tex04.jpg and /dev/null differ diff --git a/examples/wip/filters/tex05.jpg b/examples/wip/filters/tex05.jpg deleted file mode 100644 index 5bf0e3568..000000000 Binary files a/examples/wip/filters/tex05.jpg and /dev/null differ diff --git a/examples/wip/filters/tex06.jpg b/examples/wip/filters/tex06.jpg deleted file mode 100644 index 47f05af05..000000000 Binary files a/examples/wip/filters/tex06.jpg and /dev/null differ diff --git a/examples/wip/filters/tex07.jpg b/examples/wip/filters/tex07.jpg deleted file mode 100644 index 3c803d2fe..000000000 Binary files a/examples/wip/filters/tex07.jpg and /dev/null differ diff --git a/examples/wip/filters/tex08.jpg b/examples/wip/filters/tex08.jpg deleted file mode 100644 index 1c8fa6d02..000000000 Binary files a/examples/wip/filters/tex08.jpg and /dev/null differ diff --git a/examples/wip/filters/tex09.jpg b/examples/wip/filters/tex09.jpg deleted file mode 100644 index ea111ea33..000000000 Binary files a/examples/wip/filters/tex09.jpg and /dev/null differ diff --git a/examples/wip/filters/tex10.png b/examples/wip/filters/tex10.png deleted file mode 100644 index 607388333..000000000 Binary files a/examples/wip/filters/tex10.png and /dev/null differ diff --git a/examples/wip/filters/tex11.png b/examples/wip/filters/tex11.png deleted file mode 100644 index a02f0a068..000000000 Binary files a/examples/wip/filters/tex11.png and /dev/null differ diff --git a/examples/wip/filters/tex12.png b/examples/wip/filters/tex12.png deleted file mode 100644 index 93567a83d..000000000 Binary files a/examples/wip/filters/tex12.png and /dev/null differ diff --git a/examples/wip/filters/tex14.png b/examples/wip/filters/tex14.png deleted file mode 100644 index f6938f4ef..000000000 Binary files a/examples/wip/filters/tex14.png and /dev/null differ diff --git a/examples/wip/filters/tex15.png b/examples/wip/filters/tex15.png deleted file mode 100644 index bcc1ef088..000000000 Binary files a/examples/wip/filters/tex15.png and /dev/null differ diff --git a/examples/wip/filters/tex16.png b/examples/wip/filters/tex16.png deleted file mode 100644 index 32a561c7f..000000000 Binary files a/examples/wip/filters/tex16.png and /dev/null differ diff --git a/examples/wip/filters/trippyLinesFilter.js b/examples/wip/filters/trippyLinesFilter.js deleted file mode 100644 index 3b108d825..000000000 --- a/examples/wip/filters/trippyLinesFilter.js +++ /dev/null @@ -1,132 +0,0 @@ -PIXI.TrippyLinesFilter = function(width, height) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates } - }; - - // Shader by aji (https://www.shadertoy.com/view/lslGRj) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "// add any extra uniforms here", - - - - "int schedule = 0;", - - "vec4 hue(float rad)", - "{", - "rad /= 2.0;", - "return vec4(abs(cos(rad)), abs(cos(rad+1.05)),", - "abs(cos(rad+2.09)), 1.0);", - "}", - - "vec4 gradient(float f)", - "{", - "f = mod(f, 1.0) * 3.14;", - "if (schedule == 0) {", - "return vec4(sin(f) * sin(f));", - "} else if (schedule == 1) {", - "float r = pow(.5 + .5 * sin(2.0 * (f + 0.00)), 20.0);", - "float g = pow(.5 + .5 * sin(2.0 * (f + 1.05)), 20.0);", - "float b = pow(.5 + .5 * sin(2.0 * (f + 2.09)), 20.0);", - "return vec4(r, g, b, 1.0);", - "} else if (schedule == 2) {", - "return vec4(0.0, .5+.5*sin(f), 0.0, 1.0);", - "}", - "return vec4(0.0);", - "}", - - "float offset(float th)", - "{", - "float mt = mod(iGlobalTime, 4.0);", - "float x = sin(iGlobalTime + th) + sin(iGlobalTime + 2.0 * th)", - "+ .3 * cos(iGlobalTime + 8.0 * th);", - "if (schedule == 0) {", - "return x + .2 * sin(10.0 * iGlobalTime + 20.0 * th);", - "} else if (schedule == 1) {", - "return x + floor(iGlobalTime * 3.0) * .333;", - "} else if (schedule == 2) {", - "return x + .1 * sin(60.0 * th);", - "}", - "return 0.0;", - "}", - - "vec4 tunnel(float th, float radius)", - "{", - "return gradient(offset(th) + log(6.0 * radius));", - "}", - - "void main()", - "{", - "vec2 uv = gl_FragCoord.xy / iResolution.x +", - "vec2(-.5, -.5 * iResolution.y / iResolution.x);", - "schedule = int(mod(iGlobalTime + 2.0, 6.0) / 2.0);", - "gl_FragColor = tunnel(atan(uv.y, uv.x), 2.0 * length(uv));", - "}"]; - -} - -PIXI.TrippyLinesFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.TrippyLinesFilter.prototype.constructor = PIXI.TrippyLinesFilter; - -Object.defineProperty(PIXI.TrippyLinesFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/64x64.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.TrippyLinesFilter(sprite.width, sprite.height); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/tunnelFilter.js b/examples/wip/filters/tunnelFilter.js deleted file mode 100644 index 4d0340e82..000000000 --- a/examples/wip/filters/tunnelFilter.js +++ /dev/null @@ -1,157 +0,0 @@ -PIXI.TunnelFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: 'f3', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: 'f', value: 1 }, - iDate: { type: 'f4', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, wrap: 'nearest-repeat' } - }; - - // Shader by reiska (https://www.shadertoy.com/view/4sX3z7) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "void main(void)", - "{", - "float cameraPinch = 1.0; // values between 0 - 2, this will modify (pinch) the view", - "float cameraZPinch = 1.0; //", - "float cameraZFactor = 1.0; // 0-1", - "float zoomFactor = 1.0; // large values will create a kaleidoscopic effect!", - - "float texCoordUScale = 0.125;", - "float texCoordVScale = 1.0;", - - "float texCoordUMoveSpeed = 0.20;", - "float texCoordVMoveSpeed = -0.125;", - - "float cameraRotationSpeed = 0.5; // 0.0 to switch off rotation (look straight ahead)", - - "float tunnelPinch = 2.0; // 1.0 = round tunnel, change the value to modify the shape", - - "float spikeCount = 5.0;", - "float spikeFactor = sin(iGlobalTime) * 0.1; // 0.0 to switch off spikes", - - "vec3 fogColor = vec3(0.0, 0.0, 0.0);", - "float fogPower = 10.0;", - - "vec2 coord = 2.0 * ((gl_FragCoord.xy / iResolution.xy) - vec2(0.5, 0.5));", - - "float aspectRatio = iResolution.x / iResolution.y;", - - "coord.x *= aspectRatio;", - "coord *= zoomFactor;", - - "coord = vec2(sign(coord.x) * pow(abs(coord.x), cameraPinch), sign(coord.y) * pow(abs(coord.y), cameraPinch));", - - "// camera angles", - "float camAng = iGlobalTime * cameraRotationSpeed;", - - "// camera rotation vectors", - "vec3 cx = vec3(cos(camAng), 0.0, -sin(camAng));", - "vec3 cy = vec3(0.0, 1.0, 0.0);", - "vec3 cz = vec3(sin(camAng), 0.0, cos(camAng));", - - "mat3 cameraRot =", - "mat3(", - "cx.x, cx.y, cx.z,", - "cy.x, cy.y, cy.z,", - "cz.x, cz.y, cz.z);", - - "vec3 cameraDir = normalize(vec3(sin(coord.x), sin(coord.y), cos(coord.x) * cos(coord.y)));", - - "cameraDir = cameraRot * cameraDir;", - - "float angle = atan(cameraDir.x, cameraDir.y);", - "cameraDir.z *= 1.0 + sin(angle * spikeCount) * spikeFactor;", - - "cameraDir.z = cameraZFactor * sign(cameraDir.z) * pow(abs(cameraDir.z), cameraZPinch);", - - - "vec3 cameraOrigin = vec3(0.0, 0.0, 0.0);", - - "float l = sqrt(pow(cameraDir.x * cameraDir.x, tunnelPinch) + pow(cameraDir.y * cameraDir.y, tunnelPinch));", - "float d = 1.0 / l;", - - "vec3 hitPos = cameraOrigin + cameraDir * d;", - - - "vec2 uv = vec2(hitPos.z, angle / 3.14159);", - "uv.x = uv.x * texCoordUScale + iGlobalTime * texCoordUMoveSpeed;", - "uv.y = uv.y * texCoordVScale + iGlobalTime * texCoordVMoveSpeed;", - "vec3 color = texture2D(iChannel0, uv).rgb;", - - "float alpha = 1.0 - pow(min(1.0, abs(cameraDir.z)), fogPower);", - - "color = fogColor * (1.0 - alpha) + color * alpha;", - - "gl_FragColor = vec4(color, 1.0);", - "}"]; - - - -} - -PIXI.TunnelFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.TunnelFilter.prototype.constructor = PIXI.TunnelFilter; - -Object.defineProperty(PIXI.TunnelFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex15.png'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.TunnelFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/tunnel_demo.js b/examples/wip/filters/tunnel_demo.js deleted file mode 100644 index 9ce48f604..000000000 --- a/examples/wip/filters/tunnel_demo.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update }); - -var background; -var filter; - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser.png'); - game.load.image('texture2', 'wip/tex00.jpg'); - game.load.image('texture', 'assets/textures/ooze.png'); - game.load.script('tunnel', '../filters/Tunnel.js'); - -} - -function create() { - - background = game.add.sprite(0, 0, 'texture'); - background.width = 800; - background.height = 600; - - filter = game.add.filter('Tunnel', 800, 600, background.texture); - - // You have the following value to play with (default value is 2.0): - filter.origin = 1.0; - - background.filters = [filter]; - - var logo = game.add.sprite(game.world.centerX, game.world.centerY, 'phaser'); - logo.anchor.setTo(0.5, 0.5); - -} - -function update() { - - filter.update(); - - // Uncomment for coolness :) - filter.origin = filter.origin + 0.001; - -} diff --git a/examples/wip/filters/vortexFilter.js b/examples/wip/filters/vortexFilter.js deleted file mode 100644 index 769af791a..000000000 --- a/examples/wip/filters/vortexFilter.js +++ /dev/null @@ -1,111 +0,0 @@ -PIXI.VortexFilter = function(width, height, texture) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture, textureData: { repeat: true } } - }; - - // Shader by GhettoWolf (https://www.shadertoy.com/view/Xdl3WH) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "// add any extra uniforms here", - - "#ifdef GL_ES", - "precision highp float;", - "#endif", - - "#define PI 3.1416", - - "void main(void)", - "{", - "//map the xy pixel co-ordinates to be between -1.0 to +1.0 on x and y axes", - "//and alter the x value according to the aspect ratio so it isn't 'stretched'", - "vec2 p = (2.0 * gl_FragCoord.xy / iResolution.xy - 1.0)", - "* vec2(iResolution.x / iResolution.y, 1.0);", - - "//now, this is the usual part that uses the formula for texture mapping a ray-", - "//traced cylinder using the vector p that describes the position of the pixel", - "//from the centre.", - "vec2 uv = vec2(atan(p.y, p.x) * 1.0/PI, 1.0 / sqrt(dot(p, p))) * vec2(2.0, 1.0);", - - - "//now this just 'warps' the texture read by altering the u coordinate depending on", - "//the val of the v coordinate and the current time", - "uv.x += sin(2.0 * uv.y + iGlobalTime * 0.5);", - - "vec3 c = texture2D(iChannel0, uv).xyz", - - "//this divison makes the color value 'darker' into the distance, otherwise", - "//everything will be a uniform brightness and no sense of depth will be present.", - "/ (uv.y * 0.5 + 1.0);", - - "gl_FragColor = vec4(c, 1.0);", - "}"]; - -} - -PIXI.VortexFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.VortexFilter.prototype.constructor = PIXI.VortexFilter; - -Object.defineProperty(PIXI.VortexFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture', 'wip/tex00.jpg'); - -} - -var filter; -var sprite; - -function create() { - - sprite = game.add.sprite(0, 0, 'texture'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.VortexFilter(sprite.width, sprite.height, sprite.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/filters/wobbleFilter.js b/examples/wip/filters/wobbleFilter.js deleted file mode 100644 index 1e69fe051..000000000 --- a/examples/wip/filters/wobbleFilter.js +++ /dev/null @@ -1,103 +0,0 @@ -PIXI.WobbleFilter = function(width, height, texture0, texture1) -{ - PIXI.AbstractFilter.call( this ); - - this.passes = [this]; - - var d = new Date(); - - var dates = [ - d.getFullYear(), // the year (four digits) - d.getMonth(), // the month (from 0-11) - d.getDate(), // the day of the month (from 1-31) - d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds() - ]; - - this.uniforms = { - iResolution: { type: '3f', value: { x: width, y: height, z: 0 }}, - iGlobalTime: { type: '1f', value: 1 }, - iDate: { type: '4fv', value: dates }, - iChannel0: { type: 'sampler2D', value: texture0, textureData: { repeat: true } }, - iChannel1: { type: 'sampler2D', value: texture1, textureData: { repeat: true } } - }; - - // Shader by deps (https://www.shadertoy.com/view/MssGDM) - this.fragmentSrc = [ - "precision mediump float;", - "uniform vec3 iResolution;", - "uniform float iGlobalTime;", - "uniform float iChannelTime[4];", - "uniform vec4 iMouse;", - "uniform vec4 iDate;", - "uniform vec3 iChannelResolution[4];", - "uniform sampler2D iChannel0;", - "uniform sampler2D iChannel1;", - "// add any extra uniforms here", - - "void main(void)", - "{", - "vec2 uv = (gl_FragCoord.xy / iResolution.xy);", - "uv.y = 1.0-uv.y;", - - "float time = iGlobalTime * 0.75;", - - "vec4 pixel2 = texture2D(iChannel1, (uv+vec2(sin(time),cos(time))) * 0.15 );", - - "float xDiff = pixel2.r * 0.02;", - "float yDiff = 0.0;", - - "vec2 diffVec = vec2( xDiff, yDiff );", - - "vec4 pixel = texture2D(iChannel0, uv + diffVec);", - - "gl_FragColor = pixel;", - "}"]; - -} - -PIXI.WobbleFilter.prototype = Object.create( PIXI.AbstractFilter.prototype ); -PIXI.WobbleFilter.prototype.constructor = PIXI.WobbleFilter; - -Object.defineProperty(PIXI.WobbleFilter.prototype, 'iGlobalTime', { - get: function() { - return this.uniforms.iGlobalTime.value; - }, - set: function(value) { - this.uniforms.iGlobalTime.value = value; - } -}); - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('texture0', 'wip/tex04.jpg'); - game.load.image('texture1', 'wip/tex10.png'); - -} - -var filter; -var sprite; - -function create() { - - noise = game.add.sprite(0, 0, 'texture1'); - - sprite = game.add.sprite(0, 0, 'texture0'); - sprite.width = 800; - sprite.height = 600; - - filter = new PIXI.WobbleFilter(sprite.width, sprite.height, sprite.texture, noise.texture); - - sprite.filters = [filter]; - -} - -function update() { - - filter.iGlobalTime = game.time.totalElapsedSeconds(); - -} - -function render() { -} diff --git a/examples/wip/fixed to cam scale.js b/examples/wip/fixed to cam scale.js deleted file mode 100644 index 7e11aded6..000000000 --- a/examples/wip/fixed to cam scale.js +++ /dev/null @@ -1,95 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - game.load.bitmapFont('desyrel', 'assets/fonts/bitmapFonts/desyrel.png', 'assets/fonts/bitmapFonts/desyrel.xml', null, 0, -32); - -} - -var cursors; -var mushroom; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.image(0, 0, 'backdrop'); - - mushroom = game.add.sprite(100, 100, 'mushroom'); - - // Test Fixing an Image to the Camera - var fixie = game.add.image(100, 100, 'coke'); - fixie.fixedToCamera = true; - - // And tween it - game.add.tween(fixie.cameraOffset).to({ y: 500 }, 2000, Phaser.Easing.Bounce.Out, true, 0, 1000, true); - - // Test Fixing a Sprite to the Camera - var fixie2 = game.add.sprite(600, 100, 'coke'); - fixie2.fixedToCamera = true; - fixie2.inputEnabled = true; - fixie2.events.onInputDown.add(clicked, this); - - // Test Fixing a Text to the Camera - var text = game.add.text(300, 32, '-phaser-'); - text.fixedToCamera = true; - - // Test fixing a BitmapText to the Camera - var text2 = game.add.bitmapText(200, 500, 'desyrel', 'camera fixies', 32); - text2.fixedToCamera = true; - - // Test fixing a Graphics object to the Camera - var graphics = game.add.graphics(0, 0); - graphics.fixedToCamera = true; - graphics.beginFill(0xFF3300); - graphics.lineStyle(2, 0x0000FF, 1); - graphics.drawRect(50, 250, 100, 100); - - // Button! do mouse events still work then? - - // game.world.pivot.set(400, 300); - // game.camera.scale.set(2); - - game.camera.follow(mushroom); - game.camera.deadzone = new Phaser.Rectangle(200, 150, 400, 300); - // game.camera.deadzone = new Phaser.Rectangle(0, 0, 800, 600); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function clicked() { - - console.log('boom'); - -} - -function update() { - - if (cursors.left.isDown) - { - mushroom.x -= 8; - } - else if (cursors.right.isDown) - { - mushroom.x += 8; - } - - if (cursors.up.isDown) - { - mushroom.y -= 8; - } - else if (cursors.down.isDown) - { - mushroom.y += 8; - } - -} - -function render() { - - -} diff --git a/examples/wip/fixed to cam.js b/examples/wip/fixed to cam.js deleted file mode 100644 index 08920976d..000000000 --- a/examples/wip/fixed to cam.js +++ /dev/null @@ -1,90 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - game.load.bitmapFont('desyrel', 'assets/fonts/desyrel.png', 'assets/fonts/desyrel.xml', null, 0, -32); - -} - -var cursors; -var mushroom; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.image(0, 0, 'backdrop'); - - mushroom = game.add.sprite(400, 400, 'mushroom'); - - // Test Fixing an Image to the Camera - var fixie = game.add.image(100, 100, 'coke'); - fixie.fixedToCamera = true; - - // And tween it - game.add.tween(fixie.cameraOffset).to({ y: 500 }, 2000, Phaser.Easing.Bounce.Out, true, 0, 1000, true); - - // Test Fixing a Sprite to the Camera - var fixie2 = game.add.sprite(600, 100, 'coke'); - fixie2.fixedToCamera = true; - fixie2.inputEnabled = true; - fixie2.events.onInputDown.add(clicked, this); - - // Test Fixing a Text to the Camera - var text = game.add.text(300, 32, '-phaser-'); - text.fixedToCamera = true; - - // Test fixing a BitmapText to the Camera - var text2 = game.add.bitmapText(200, 500, 'desyrel', 'camera fixies', 32); - text2.fixedToCamera = true; - - // Test fixing a Graphics object to the Camera - var graphics = game.add.graphics(0, 0); - graphics.fixedToCamera = true; - graphics.beginFill(0xFF3300); - graphics.lineStyle(2, 0x0000FF, 1); - graphics.drawRect(50, 250, 100, 100); - - // Button! do mouse events still work then? - - game.camera.follow(mushroom); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function clicked() { - - console.log('boom'); - -} - -function update() { - - if (cursors.left.isDown) - { - mushroom.x -= 8; - } - else if (cursors.right.isDown) - { - mushroom.x += 8; - } - - if (cursors.up.isDown) - { - mushroom.y -= 8; - } - else if (cursors.down.isDown) - { - mushroom.y += 8; - } - -} - -function render() { - - -} diff --git a/examples/wip/focus mute.js b/examples/wip/focus mute.js deleted file mode 100644 index 06c353513..000000000 --- a/examples/wip/focus mute.js +++ /dev/null @@ -1,53 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('disk', 'assets/sprites/ra_dont_crack_under_pressure.png'); - - // Firefox doesn't support mp3 files, so use ogg - game.load.audio('boden', ['assets/audio/bodenstaendig_2000_in_rock_4bit.mp3', 'assets/audio/bodenstaendig_2000_in_rock_4bit.ogg']); - -} - -var s; -var music; - -function create() { - - game.stage.backgroundColor = '#182d3b'; - game.input.touch.preventDefault = false; - - music = game.add.audio('boden'); - music.play(); - - s = game.add.sprite(game.world.centerX, game.world.centerY, 'disk'); - s.anchor.setTo(0.5, 0.5); - - game.input.onDown.add(changeVolume, this); - -} - -function changeVolume(pointer) { - - if (pointer.y < 300) - { - game.sound.volume += 0.1; - // music.volume += 0.1; - } - else - { - game.sound.volume -= 0.1; - // music.volume -= 0.1; - } - -} - -function update() { - s.rotation += 0.01; -} - -function render() { - game.debug.soundInfo(music, 20, 32); -} - diff --git a/examples/wip/frame.js b/examples/wip/frame.js deleted file mode 100644 index 4637dbcd5..000000000 --- a/examples/wip/frame.js +++ /dev/null @@ -1,55 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var mummy; -var jelly; - -function create() { - - // Testing both sprite sheets and texture atlases with a Phaser.Image - - mummy = game.add.image(200, 200, 'mummy'); - - jelly = game.add.image(200, 300, 'seacreatures', 'blueJellyfish0000'); - - game.input.onDown.add(changeFrame, this); - -} - -function changeFrame() { - - if (jelly.frameName === 'blueJellyfish0000') - { - jelly.frameName = 'crab10000'; - } - else if (jelly.frameName === 'crab10000') - { - jelly.frameName = 'purpleFish0000'; - } - else - { - jelly.frameName = 'blueJellyfish0000'; - } - -} - -function update() { - - // You could animate an Image like this! But it makes more sense to use a Sprite - if (mummy.frame < 17) - { - mummy.frame++; - } - else - { - mummy.frame = 0; - } - -} \ No newline at end of file diff --git a/examples/wip/fullscreen.js b/examples/wip/fullscreen.js deleted file mode 100644 index 394ac5f29..000000000 --- a/examples/wip/fullscreen.js +++ /dev/null @@ -1,79 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('dragon', 'assets/pics/cougar_dragonsun.png'); - game.load.spritesheet('button', 'assets/buttons/button_sprite_sheet.png', 193, 71); - -} - -var button; -var sprite; - -function create() { - - sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'dragon'); - sprite.anchor.set(0.5); - - game.stage.backgroundColor = '#000'; - - // Stretch to fill - game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT; - - // Keep original size - // game.scale.fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE; - - // Maintain aspect ratio - // game.scale.fullScreenScaleMode = Phaser.ScaleManager.SHOW_ALL; - - button = game.add.button(game.world.centerX - 95, 500, 'button', actionOnClick, this, 2, 1, 0); - button.visible = false; - - game.scale.enterFullScreen.add(onEnterFullScreen, this); - game.scale.leaveFullScreen.add(onLeaveFullScreen, this); - - game.input.onDown.add(gofull, this); - -} - -function onEnterFullScreen() { - - button.visible = true; - -} - -function onLeaveFullScreen() { - - button.visible = false; - -} - -function gofull() { - - game.scale.startFullScreen(false); - -} - -function actionOnClick () { - - sprite.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - -} - -function render () { - - if (game.scale.isFullScreen) - { - game.debug.text('ESC to leave fullscreen', 270, 16); - } - else - { - game.debug.text('Click / Tap to go fullscreen', 270, 16); - } - -} diff --git a/examples/wip/google webfont.js b/examples/wip/google webfont.js deleted file mode 100644 index 4b9f5ae7c..000000000 --- a/examples/wip/google webfont.js +++ /dev/null @@ -1,72 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create }); - -// The Google WebFont Loader will look for this object, so create it before loading the script. -WebFontConfig = { - - // 'active' means all requested fonts have finished loading - // We set a 1 second delay before calling 'createText'. - // For some reason if we don't the browser cannot render the text the first time it's created. - active: function() { game.time.events.add(Phaser.Timer.SECOND, createText, this); }, - - // The Google Fonts we want to load - google: { - families: ['Revalia', 'Droid Sans', 'Droid Serif'] - } - -}; - -function preload() { - - // Load the Google WebFont Loader script - game.load.script('webfont', '//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js'); - -} - -var text = null; -var grd; - -function create() { - - game.stage.setBackgroundColor(0x2d2d2d); - -} - -function createText() { - - text = game.add.text(game.world.centerX, game.world.centerY, "- phaser -\nrocking with\ngoogle web fonts"); - text.anchor.setTo(0.5); - - text.font = 'Revalia'; - text.fontSize = 60; - - // x0, y0 - x1, y1 - grd = text.context.createLinearGradient(0, 0, 0, text.canvas.height); - grd.addColorStop(0, '#8ED6FF'); - grd.addColorStop(1, '#004CB3'); - text.fill = grd; - - text.align = 'center'; - text.stroke = '#000000'; - text.strokeThickness = 2; - text.setShadow(5, 5, 'rgba(0,0,0,0.5)', 5); - - text.inputEnabled = true; - text.input.enableDrag(); - - text.events.onInputOver.add(over, this); - text.events.onInputOut.add(out, this); - -} - -function out() { - - text.fill = grd; - -} - -function over() { - - text.fill = '#ff00ff'; - -} diff --git a/examples/wip/graphics-mask.js b/examples/wip/graphics-mask.js deleted file mode 100644 index 85ebff6e0..000000000 --- a/examples/wip/graphics-mask.js +++ /dev/null @@ -1,40 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - -} - -var atari1; -var graphics; - -function create() { - - atari1 = game.add.sprite(50, 50, 'atari'); - - graphics = game.add.graphics(0, 0); - - graphics.beginFill(0xFF3300); - graphics.moveTo(0,50); - graphics.lineTo(250, 50); - graphics.lineTo(100, 100); - graphics.lineTo(250, 220); - graphics.lineTo(50, 220); - graphics.lineTo(0, 50); - graphics.endFill(); - - atari1.mask = graphics; - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/graphics.js b/examples/wip/graphics.js deleted file mode 100644 index f7a82dc6c..000000000 --- a/examples/wip/graphics.js +++ /dev/null @@ -1,69 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { create: create, update: update }); - -var graphics; -var sprite; - -function create() { - - graphics = game.add.graphics(0, 0); - // we don't need it to render, we're just using it as a texture - graphics.visible = false; - - // set a fill and line style - graphics.beginFill(0xFF3300); - graphics.lineStyle(10, 0xffd900, 1); - - // draw a shape - graphics.moveTo(0,50); - graphics.lineTo(250, 50); - graphics.lineTo(100, 100); - graphics.lineTo(250, 220); - graphics.lineTo(50, 220); - graphics.lineTo(0, 50); - graphics.endFill(); - - // set a fill and line style again - graphics.lineStyle(10, 0xFF0000, 0.8); - graphics.beginFill(0xFF700B, 1); - - // draw a second shape - graphics.moveTo(210,300); - graphics.lineTo(450,320); - graphics.lineTo(570,350); - graphics.lineTo(580,20); - graphics.lineTo(330,120); - graphics.lineTo(410,200); - graphics.lineTo(210,300); - graphics.endFill(); - - // draw a rectangle - graphics.lineStyle(2, 0x0000FF, 1); - graphics.drawRect(50, 250, 100, 100); - - sprite = game.add.sprite(100, 100, graphics.generateTexture()); - - // graphics.inputEnabled = true; - // graphics.events.onInputDown.add(clicked, this); - -} - -function clicked() { - - console.log('boom'); - - // draw a circle - graphics.lineStyle(0); - graphics.beginFill(0xFFFF0B, 0.5); - graphics.drawCircle(470, 200,100); - - graphics.lineStyle(20, 0x33FF00); - graphics.moveTo(30,30); - graphics.lineTo(600, 300); - -} - -function update() { - - - -} \ No newline at end of file diff --git a/examples/wip/grid-drag.js b/examples/wip/grid-drag.js deleted file mode 100644 index 7a7a24b0e..000000000 --- a/examples/wip/grid-drag.js +++ /dev/null @@ -1,86 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('block', 'assets/sprites/block.png'); - -} - -var grid = []; -var currentTile = new Phaser.Point(); - -function create() { - - // The block.png is 95x95, so for this we'll create a little grid or it won't fit: - - for (var y = 0; y < 5; y++) - { - grid[y] = []; - - for (var x = 0; x < 5; x++) - { - // grid[y][x] = game.add.sprite(x * 95, y * 95, 'block'); - // coz the grid is empty like - grid[y][x] = null; - } - } - - var block1 = game.add.sprite(600, 100, 'block'); - block1.name = 'block1'; - block1.inputEnabled = true; - block1.input.enableDrag(true); - block1.events.onDragStop.add(dropBlock, this); - - var block2 = game.add.sprite(600, 300, 'block'); - block2.name = 'block2'; - block2.inputEnabled = true; - block2.input.enableDrag(true); - block2.events.onDragStop.add(dropBlock, this); - -} - -function dropBlock(sprite, pointer) { - - // Convert the pointer into a grid location - var x = this.game.math.snapToFloor(pointer.x, 95) / 95; - var y = this.game.math.snapToFloor(pointer.y, 95) / 95; - - // Bounds check it - if (x >= 0 && x <= 4 && y >= 0 && y <= 4) - { - // something in there already? - if (grid[y][x] !== null) - { - // This is very hacky - what you SHOULD do is have a Pipe object which has properties startX and startY or something, and snap back to those. - if (sprite.name === 'block1') - { - game.add.tween(sprite).to( { x: 600, y: 100 }, 1000, Phaser.Easing.Linear.None, true); - } - else - { - game.add.tween(sprite).to( { x: 600, y: 300 }, 1000, Phaser.Easing.Linear.None, true); - } - } - else - { - grid[y][x] = sprite; - sprite.inputEnabled = false; - } - } - -} - -function update() { - - // 95 = width and height of the block.png - currentTile.x = this.game.math.snapToFloor(game.input.x, 95) / 95; - currentTile.y = this.game.math.snapToFloor(game.input.y, 95) / 95; - -} - -function render() { - - game.debug.text('Tile X: ' + currentTile.x + ' Y: ' + currentTile.y, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/grid.js b/examples/wip/grid.js deleted file mode 100644 index fe2c6c7d6..000000000 --- a/examples/wip/grid.js +++ /dev/null @@ -1,54 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('block', 'assets/sprites/block.png'); - -} - -var grid = []; -var currentTile = new Phaser.Point(); - -function create() { - - // The block.png is 95x95, so for this we'll create a little grid or it won't fit: - - for (var y = 0; y < 5; y++) - { - grid[y] = []; - - for (var x = 0; x < 5; x++) - { - grid[y][x] = game.add.sprite(x * 95, y * 95, 'block'); - } - } - - game.input.onDown.add(clickedBlock, this); - -} - -function clickedBlock() { - - // Bounds check - if (currentTile.x >= 0 && currentTile.x <= 4 && currentTile.y >= 0 && currentTile.y <= 4) - { - block = grid[currentTile.y][currentTile.x]; - block.alpha = 0.5; - } - -} - -function update() { - - // 95 = width and height of the block.png - currentTile.x = this.game.math.snapToFloor(game.input.x, 95) / 95; - currentTile.y = this.game.math.snapToFloor(game.input.y, 95) / 95; - -} - -function render() { - - game.debug.text('Tile X: ' + currentTile.x + ' Y: ' + currentTile.y, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/group destroy.js b/examples/wip/group destroy.js deleted file mode 100644 index b75d1cfa3..000000000 --- a/examples/wip/group destroy.js +++ /dev/null @@ -1,72 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.bitmapFont('carrier', 'assets/fonts/carrier_command.png', 'assets/fonts/carrier_command.xml', null, 0, 24); - game.load.spritesheet('button', 'assets/buttons/button_sprite_sheet.png', 193, 71); - -} - -var group; -var DaddyGroup; - -function create() { - - DaddyGroup = game.add.group(); - - group = game.add.group(); - - // Testing Group.destroy with different object types: - - var sprite = game.make.sprite(300, 100, 'atari1'); - - var graphics = game.make.graphics(0, 0); - graphics.beginFill(0xFF3300); - graphics.moveTo(0,50); - graphics.lineTo(250, 50); - graphics.lineTo(100, 100); - graphics.lineTo(250, 220); - graphics.lineTo(50, 220); - graphics.lineTo(0, 50); - graphics.endFill(); - - var tilesprite = game.make.tileSprite(600, 100, 200, 200, 'starfield'); - tilesprite.autoScroll(0, 100); - - var bitmaptext = game.make.bitmapText(100, 300, 'carrier', 'bitmap text', 32); - - var text = game.make.text(100, 350, "normal text"); - text.font = 'Arial Black'; - text.fontSize = 60; - text.fill = '#ff0044'; - - var button = game.make.button(100, 450, 'button', actionOnClick, this, 2, 1, 0); - - group.add(sprite); - group.add(graphics); - group.add(tilesprite); - group.add(bitmaptext); - group.add(text); - group.add(button); - - DaddyGroup.add(group); - - game.input.onDown.add(actionOnClick, this); - -} - -function actionOnClick() { - - DaddyGroup.destroy(); - -} - -function update() { -} - -function render() { -} diff --git a/examples/wip/group fixed to cam.js b/examples/wip/group fixed to cam.js deleted file mode 100644 index 4b1af98dc..000000000 --- a/examples/wip/group fixed to cam.js +++ /dev/null @@ -1,68 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - -} - -var cursors; -var mushroom; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.image(0, 0, 'backdrop'); - - mushroom = game.add.sprite(400, 400, 'mushroom'); - - var group = game.add.group(); - - for (var i = 0; i < 20; i++) - { - group.create(Math.random() * 800, Math.random() * 600, 'coke'); - } - - group.fixedToCamera = true; - - game.camera.follow(mushroom); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function clicked() { - - console.log('boom'); - -} - -function update() { - - if (cursors.left.isDown) - { - mushroom.x -= 8; - } - else if (cursors.right.isDown) - { - mushroom.x += 8; - } - - if (cursors.up.isDown) - { - mushroom.y -= 8; - } - else if (cursors.down.isDown) - { - mushroom.y += 8; - } - -} - -function render() { - - -} diff --git a/examples/wip/group lifespan.js b/examples/wip/group lifespan.js deleted file mode 100644 index 1abfb0689..000000000 --- a/examples/wip/group lifespan.js +++ /dev/null @@ -1,59 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - -} - -var group1; -var group2; -var cursors; - -function create() { - - group1 = game.add.group(); - group2 = game.add.group(); - - // Now let's create some random sprites and enable them all for drag and 'bring to top' - var t; - - for (var i = 0; i < 10; i++) - { - t = group1.create(game.world.randomX, game.world.randomY, 'atari1'); - t.lifespan = 3000 + (Math.random() * 3000); - - group2.create(game.world.randomX, game.world.randomY, 'sonic'); - } - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - group1.x -= 4; - } - else if (cursors.right.isDown) - { - group1.x += 4; - } - - if (cursors.up.isDown) - { - group2.y -= 4; - } - else if (cursors.down.isDown) - { - group2.y += 4; - } - -} - -function render() { - // game.debug.inputInfo(32, 32); -} diff --git a/examples/wip/group1.js b/examples/wip/group1.js deleted file mode 100644 index 11f0e58c6..000000000 --- a/examples/wip/group1.js +++ /dev/null @@ -1,56 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - -} - -var group1; -var group2; -var cursors; - -function create() { - - group1 = game.add.group(); - group2 = game.add.group(); - - // Now let's create some random sprites and enable them all for drag and 'bring to top' - for (var i = 0; i < 10; i++) - { - group1.create(game.world.randomX, game.world.randomY, 'atari1'); - - group2.create(game.world.randomX, game.world.randomY, 'sonic'); - } - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - group1.x -= 4; - } - else if (cursors.right.isDown) - { - group1.x += 4; - } - - if (cursors.up.isDown) - { - group2.y -= 4; - } - else if (cursors.down.isDown) - { - group2.y += 4; - } - -} - -function render() { - // game.debug.inputInfo(32, 32); -} diff --git a/examples/wip/hitArea.js b/examples/wip/hitArea.js deleted file mode 100644 index 310a4132a..000000000 --- a/examples/wip/hitArea.js +++ /dev/null @@ -1,93 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('ball', 'assets/sprites/wizball.png'); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var image; -var image2; -var jellyfish; - -var down; -var p; -var c; - -function create() { - - image = game.add.image(200, 200, 'mushroom'); - image2 = game.add.image(400, 200, 'ball'); - - // image.rotation = 0.8; - - image.inputEnabled = true; - - image.events.onInputDown.add(clicked, this); - image.events.onInputOver.add(over, this); - image.events.onInputOut.add(out, this); - - - - image2.hitArea = new Phaser.Circle(image2.width / 2, image2.height / 2, 90); - image2.inputEnabled = true; - - image2.events.onInputDown.add(clicked, this); - image2.events.onInputOver.add(over, this); - image2.events.onInputOut.add(out, this); - - - - jellyfish = game.add.sprite(500, 450, 'seacreatures', 'octopus0000'); - jellyfish.inputEnabled = true; - jellyfish.anchor.set(0.5); - // jellyfish.pivot.set(jellyfish.width / 2, jellyfish.height / 2); - jellyfish.angle = 60; - jellyfish.scale.set(2); - jellyfish.input.pixelPerfectClick = true; - - jellyfish.events.onInputDown.add(clicked, this); - jellyfish.events.onInputOver.add(over, this); - jellyfish.events.onInputOut.add(out, this); - -} - -function over(object, pointer) { - - object.alpha = 0.5; - -} - -function out(object, pointer) { - - object.alpha = 1; - -} - -function clicked(object, pointer) { - - console.log('boom'); - -} - -function update() { - - -} - -function render() { - - // var p = game.input.getLocalPosition(image); - // var p = game.input.getLocalPosition(image2); - var p = game.input.getLocalPosition(jellyfish, game.input.activePointer); - - - game.debug.pointInfo(p, 32, 32); - game.debug.point(p); - game.debug.text(); - // game.debug.circle(image2.hitArea); - -} diff --git a/examples/wip/image1.js b/examples/wip/image1.js deleted file mode 100644 index 32605fa5c..000000000 --- a/examples/wip/image1.js +++ /dev/null @@ -1,45 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var image; -var sprite; - -function create() { - -console.log('wtf'); - - image = game.add.image(game.world.centerX, game.world.centerY, 'pic'); - image.anchor.set(0.5); - - // sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'pic'); - // sprite.anchor.set(0.5); - - game.input.onDown.add(tint, this); - -} - -function tint() { - - image.tint = Math.random() * 0xFFFFFF; - // sprite.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - image.angle += 1; - // sprite.angle += 1; - -} - -function render() { - - // game.debug.text(sprite.position.y, 32, 32); - -} diff --git a/examples/wip/image2.js b/examples/wip/image2.js deleted file mode 100644 index 99efd3f05..000000000 --- a/examples/wip/image2.js +++ /dev/null @@ -1,54 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var image; -var image2; -var r; - -function create() { - - image = game.add.image(32, 50, 'pic'); - - image2 = game.add.image(32, 250, 'pic'); - - r = new Phaser.Rectangle(0, 0, 100, 100); - - image2.crop(r); - - game.input.onDown.add(tint, this); - -} - -function tint() { - - image.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - if (r && r.width < 300) - { - r.width += 1; - image2.crop(r); - } - else - { - image2.crop(); - r = null; - } - -} - -function render() { - - game.debug.text(image2.width, 32, 32); - -} diff --git a/examples/wip/image3.js b/examples/wip/image3.js deleted file mode 100644 index c2332a6d4..000000000 --- a/examples/wip/image3.js +++ /dev/null @@ -1,24 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -function create() { - - // Testing both sprite sheets and texture atlases with a Phaser.Image - - for (var i = 0; i < 18; i++) - { - game.add.image(4 + 44 * i, 200, 'mummy', i); - } - - game.add.image(200, 300, 'seacreatures', 'blueJellyfish0000'); - game.add.image(300, 300, 'seacreatures', 'crab10000'); - game.add.image(470, 300, 'seacreatures', 'purpleFish0000'); - -} diff --git a/examples/wip/index-cocoon.html b/examples/wip/index-cocoon.html deleted file mode 100644 index 150aecad3..000000000 --- a/examples/wip/index-cocoon.html +++ /dev/null @@ -1,136 +0,0 @@ - - - - - phaser - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - \ No newline at end of file diff --git a/examples/wip/index-cocoon.php b/examples/wip/index-cocoon.php deleted file mode 100644 index 150aecad3..000000000 --- a/examples/wip/index-cocoon.php +++ /dev/null @@ -1,136 +0,0 @@ - - - - - phaser - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - \ No newline at end of file diff --git a/examples/wip/index-fs.php b/examples/wip/index-fs.php deleted file mode 100644 index 9788e2106..000000000 --- a/examples/wip/index-fs.php +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - phaser - - - - - - - - -
- - - \ No newline at end of file diff --git a/examples/wip/index-lib.php b/examples/wip/index-lib.php deleted file mode 100644 index c4462af60..000000000 --- a/examples/wip/index-lib.php +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - phaser - - - - - - - - - - -
- -

Back to index

- - - \ No newline at end of file diff --git a/examples/wip/index.php b/examples/wip/index.php deleted file mode 100644 index d66ecfaeb..000000000 --- a/examples/wip/index.php +++ /dev/null @@ -1,120 +0,0 @@ - $value) - { - if (is_array($value) && count($value) > 0) - { - $total += count($value); - } - } - - function getFile() { - - global $files, $dir, $filename, $title, $code; - - if (isset($_GET['d']) && isset($_GET['f'])) - { - $dir = urldecode($_GET['d']); - $filename = urldecode($_GET['d']) . '/' . urldecode($_GET['f']); - $title = urldecode($_GET['t']); - - if (file_exists($filename)) - { - $code = file_get_contents($filename); - $files = dirToArray($dir); - } - } - - } - - function dirToArray($dir) { - - $ignore = array('.', '..', '_site', 'assets', 'gfx', 'states', 'book', 'filters', 'misc'); - $result = array(); - $root = scandir($dir); - $dirs = array_diff($root, $ignore); - - foreach ($dirs as $key => $value) - { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) - { - $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); - } - else - { - if (substr($value, -3) == '.js') - { - $result[] = $value; - } - } - } - - return $result; - } - - function printJSLinks($dir, $files) { - - $output = ""; - - foreach ($files as $key => $value) - { - $value2 = substr($value, 0, -3); - $file = urlencode($value); - - $output .= "$value2"; - $output .= "[ single lib ]"; - $output .= "[ full screen ]"; - $output .= "[ cocoon ]"; - } - - return $output; - - } -?> - - - - - - phaser - - - - - - - - - -
- -
- - - -
- -
- - - \ No newline at end of file diff --git a/examples/wip/index3.php b/examples/wip/index3.php deleted file mode 100644 index a01390d97..000000000 --- a/examples/wip/index3.php +++ /dev/null @@ -1,136 +0,0 @@ - $value) - { - if (is_array($value) && count($value) > 0) - { - $total += count($value); - } - } - - function getFile() { - - global $files, $dir, $filename, $title, $code; - - if (isset($_GET['d']) && isset($_GET['f'])) - { - $dir = urldecode($_GET['d']); - $filename = urldecode($_GET['d']) . '/' . urldecode($_GET['f']); - $title = urldecode($_GET['t']); - - if (file_exists($filename)) - { - $code = file_get_contents($filename); - $files = dirToArray($dir); - } - } - - } - - function dirToArray($dir) { - - $ignore = array('.', '..', '_site', 'assets', 'gfx', 'states', 'book', 'filters', 'misc'); - $result = array(); - $root = scandir($dir); - $dirs = array_diff($root, $ignore); - - foreach ($dirs as $key => $value) - { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) - { - $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); - } - else - { - if (substr($value, -3) == '.js') - { - $result[] = $value; - } - } - } - - return $result; - } - - function printJSLinks($dir, $files) { - - $output = ""; - - foreach ($files as $key => $value) - { - $value2 = substr($value, 0, -3); - $file = urlencode($value); - - $output .= "$value2
"; - } - - return $output; - - } -?> - - - - - - phaser - - - - - - - - - -

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ullamcorper ornare sagittis. Donec eleifend pulvinar velit nec convallis. Vestibulum vitae elit dui. Donec eu tincidunt sem. Duis lectus mi, bibendum sed nunc lobortis, tincidunt sollicitudin lectus. Aliquam erat volutpat. Aliquam a lectus sed tellus sodales tempus. Suspendisse potenti. Phasellus augue nisl, placerat vel sem vel, suscipit elementum neque. Vivamus tempor vestibulum eros, vitae mattis lectus aliquet ut. Curabitur interdum, nibh quis molestie placerat, augue ipsum commodo tortor, sed blandit est augue sit amet sapien. Ut vel consequat tellus. Aenean et vulputate sapien. Praesent rutrum elementum elit ut tempor. Aliquam erat volutpat. Fusce fermentum tincidunt est non vulputate.

- -

In aliquam sed nulla id luctus. Donec ut nibh massa. Nullam aliquam feugiat urna, nec ultricies risus vulputate at. Fusce scelerisque ligula vel urna porta, nec aliquam leo facilisis. Duis accumsan nibh vestibulum, venenatis enim sit amet, condimentum sapien. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Ut auctor diam id mi porta, vestibulum pulvinar nibh sollicitudin. Curabitur ullamcorper lorem id lorem commodo, non ornare enim placerat. In vitae nisl lectus. Pellentesque eget neque sed ligula blandit porttitor vitae ut nibh. Nulla facilisi. Nunc ac erat viverra leo bibendum volutpat ut eu justo. Fusce a mollis purus. Phasellus consectetur vehicula ligula vel vestibulum. Suspendisse at dui vel ligula convallis lobortis at et tellus.

- -

Nullam aliquam erat eros, sit amet faucibus tortor iaculis ut. Sed ullamcorper dui sed dolor rutrum tincidunt. Ut sed faucibus mauris, non porta tellus. Nam ultricies vel leo eget rutrum. Sed sit amet pretium risus. Nunc ut sapien eget elit ultrices pretium quis sed justo. Donec a est vitae justo vestibulum porta. Ut interdum pharetra quam id tempor. Sed egestas placerat quam, quis ullamcorper dolor ornare non. Nulla et porttitor neque, a congue nisl. Maecenas vitae elit pretium odio euismod rhoncus. Nulla turpis libero, fermentum quis aliquet et, ultrices nec mi.

- -

Etiam vulputate, elit eu aliquet sagittis, sapien mi cursus nisi, vel mattis orci tortor non velit. Integer nisi dolor, posuere nec elit vitae, porttitor semper velit. Suspendisse sapien augue, lobortis sit amet dolor at, ornare porttitor metus. Proin venenatis ante nec augue volutpat dapibus. Sed interdum augue urna, id feugiat metus feugiat nec. In sed massa nisi. Donec iaculis nisi nulla, a pulvinar nisi dictum tristique. Nunc non erat enim. Proin consequat dolor nec leo gravida aliquet. Nulla non mollis turpis. Curabitur mollis tortor id elementum molestie. Maecenas eleifend et quam eget pellentesque.

- -

Integer ac hendrerit lorem. Nulla laoreet enim eget sem placerat, quis sagittis augue egestas. Ut porttitor purus rhoncus arcu dictum, id condimentum eros fringilla. Donec odio odio, lacinia sed ligula sit amet, viverra scelerisque libero. Curabitur pellentesque nulla mattis, egestas nibh non, viverra eros. Nullam volutpat lectus erat, quis luctus dui lobortis sit amet. Aenean ornare at sem vel pretium. Sed eu euismod nibh. Donec sed venenatis tortor.

- -
- - - - -
- -

work in progress examples

- - - -
- - - \ No newline at end of file diff --git a/examples/wip/indexNoPhysics.php b/examples/wip/indexNoPhysics.php deleted file mode 100644 index 6ea3e4125..000000000 --- a/examples/wip/indexNoPhysics.php +++ /dev/null @@ -1,116 +0,0 @@ - $value) - { - if (is_array($value) && count($value) > 0) - { - $total += count($value); - } - } - - function getFile() { - - global $files, $dir, $filename, $title, $code; - - if (isset($_GET['d']) && isset($_GET['f'])) - { - $dir = urldecode($_GET['d']); - $filename = urldecode($_GET['d']) . '/' . urldecode($_GET['f']); - $title = urldecode($_GET['t']); - - if (file_exists($filename)) - { - $code = file_get_contents($filename); - $files = dirToArray($dir); - } - } - - } - - function dirToArray($dir) { - - $ignore = array('.', '..', '_site', 'assets', 'gfx', 'states', 'book', 'filters', 'misc'); - $result = array(); - $root = scandir($dir); - $dirs = array_diff($root, $ignore); - - foreach ($dirs as $key => $value) - { - if (is_dir($dir . DIRECTORY_SEPARATOR . $value)) - { - $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value); - } - else - { - if (substr($value, -3) == '.js') - { - $result[] = $value; - } - } - } - - return $result; - } - - function printJSLinks($dir, $files) { - - $output = ""; - - foreach ($files as $key => $value) - { - $value2 = substr($value, 0, -3); - $file = urlencode($value); - - $output .= "$value2
"; - } - - return $output; - - } -?> - - - - - - phaser / no-physics - - - - - - - - - - -
- -
- -

work in progress examples

- - - -
- - - \ No newline at end of file diff --git a/examples/wip/keyboard.js b/examples/wip/keyboard.js deleted file mode 100644 index 0de5be57f..000000000 --- a/examples/wip/keyboard.js +++ /dev/null @@ -1,57 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('ship', 'assets/sprites/thrust_ship2.png'); - -} - -var ship; -var cursors; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - ship = game.add.sprite(200, 200, 'ship'); - ship.physicsEnabled = true; - // We do this because our ship is shaped like a triangle, not a square :) - ship.body.addPolygon({}, 29, 23 , 0, 23 , 14, 1); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - ship.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - ship.body.rotateRight(100); - } - else - { - ship.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - ship.body.thrust(400); - } - else if (cursors.down.isDown) - { - ship.body.reverse(400); - } - -} - -function render() { - - game.debug.physicsBody(ship.body); - -} diff --git a/examples/wip/landscape-pointer.js b/examples/wip/landscape-pointer.js deleted file mode 100644 index 8534a547f..000000000 --- a/examples/wip/landscape-pointer.js +++ /dev/null @@ -1,59 +0,0 @@ - -var game = new Phaser.Game(1024, 672, Phaser.CANVAS, 'phaser-example', { init: init, preload: preload, create: create, update: update, render: render }); - -function init() { - - game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; - game.scale.minWidth = 480; - game.scale.minHeight = 260; - game.scale.maxWidth = 1024; - game.scale.maxHeight = 768; - game.scale.forceOrientation(true, false); - game.scale.enterIncorrectOrientation.add(enterIncorrectOrientation, game); - game.scale.leaveIncorrectOrientation.add(leaveIncorrectOrientation, game); - game.scale.setScreenSize(true); - - game.stage.backgroundColor = 0x004400; - -} - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; -var anim; - -function create() { - - mummy = game.add.sprite(300, 200, 'mummy', 5); - - anim = mummy.animations.add('walk'); - - anim.play(20, true); - -} - -function enterIncorrectOrientation () { - - game.stage.backgroundColor = 0xff0000; - -} - -function leaveIncorrectOrientation () { - - game.stage.backgroundColor = 0x000033; - -} - -function update() { - -} - -function render() { - - game.debug.pointer(game.input.activePointer); - -} \ No newline at end of file diff --git a/examples/wip/line bounds.js b/examples/wip/line bounds.js deleted file mode 100644 index c285385f7..000000000 --- a/examples/wip/line bounds.js +++ /dev/null @@ -1,43 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { create: create, update: update, render: render }); - -var line; -var setting = false; - -function create() { - - line = new Phaser.Line(64, 64, 200, 300); - - game.input.onDown.add(click, this); - -} - -function update() { - - if (setting) - { - if (game.input.activePointer.isDown) - { - line.end.set(game.input.activePointer.x, game.input.activePointer.y); - } - else - { - setting = false; - } - } - -} - -function click(pointer) { - - setting = true; - line.start.set(pointer.x, pointer.y); - -} - -function render() { - - game.debug.geom(line); - game.debug.rectangle(line); - -} diff --git a/examples/wip/line points.js b/examples/wip/line points.js deleted file mode 100644 index 71050f8c1..000000000 --- a/examples/wip/line points.js +++ /dev/null @@ -1,20 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - - -function create() { - - var line = new Phaser.Line(100, 50, 10, 300); - - var coords = line.coordinatesOnLine(8); - - var bmd = game.add.bitmapData(800, 600); - bmd.context.fillStyle = '#ffffff'; - var bg = game.add.sprite(0, 0, bmd); - - for (var i = 0; i < coords.length; i++) - { - bmd.context.fillRect(coords[i][0], coords[i][1], 1, 1); - } - -} diff --git a/examples/wip/loadPolygon.js b/examples/wip/loadPolygon.js deleted file mode 100644 index 2aed1403f..000000000 --- a/examples/wip/loadPolygon.js +++ /dev/null @@ -1,45 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('contra2', 'assets/pics/contra2.png'); - game.load.image('bunny', 'assets/sprites/bunny.png'); - game.load.image('tetrisblock1', 'assets/sprites/tetrisblock1.png'); - game.load.image('tetrisblock2', 'assets/sprites/tetrisblock2.png'); - game.load.image('tetrisblock3', 'assets/sprites/tetrisblock3.png'); - - // Load our physcs data exported from PhysicsEditor - game.load.physics('physicsData', 'assets/physics/sprites.json'); - -} - -var contra; -var start = false; - -function create() { - - // Enable p2 physics - game.physics.startSystem(Phaser.Physics.P2JS); - - contra = game.add.sprite(400, 300, 'contra2'); - game.physics.enable(contra, Phaser.Physics.P2JS, true); - contra.body.clearShapes(); - contra.body.loadPolygon('physicsData', 'contra2'); - - game.input.onDown.add(function() { start = true; }, this); - -} - -function update() { - - if (start) - { - contra.body.rotateLeft(5); - } - -} - -function render() { - -} diff --git a/examples/wip/misc/2ball.js b/examples/wip/misc/2ball.js deleted file mode 100644 index b1fa2e9df..000000000 --- a/examples/wip/misc/2ball.js +++ /dev/null @@ -1,422 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('chunk', 'assets/sprites/chunk.png'); - game.load.image('arrow', 'assets/sprites/asteroids_ship.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - -} - -var sprite; -var sprite2; -var sprite3; -var group; -var flag = false; - -var bmd; - -function create() { - - game.stage.backgroundColor = '#124184'; - - bmd = game.add.bitmapData(800, 600); - bmd.fillStyle('#ffffff'); - var bg = game.add.sprite(0, 0, bmd); - bg.body.moves = false; - - test12(); - -} - -function test12() { - - // game.physics.gravity.y = 150; - - sprite = game.add.sprite(200, 300, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.checkCollision.right = false; - // sprite.body.checkCollision.up = false; - // sprite.body.immovable = true; - - sprite2 = game.add.sprite(400, 358, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch12, this); - -} - -function launch12() { - - sprite2.body.velocity.x = -200; - // sprite2.body.velocity.y = -60; - -} - -function test11() { - - // game.physics.gravity.y = 150; - - sprite = game.add.sprite(300, 200, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - // sprite.body.checkCollision.down = false; - // sprite.body.checkCollision.up = false; - sprite.body.checkCollision.right = false; - // sprite.body.immovable = true; - - sprite2 = game.add.sprite(290, 400, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch11, this); - -} - -function launch11() { - - sprite2.body.velocity.y = -200; - -} - -function test10() { - - // game.physics.gravity.y = 150; - - sprite = game.add.sprite(300, 200, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.checkCollision.down = false; - - sprite2 = game.add.sprite(330, 400, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch10, this); - -} - -function launch10() { - - sprite2.body.velocity.y = -100; - -} - -function test9() { - - // game.physics.gravity.y = 150; - - sprite = game.add.sprite(300, 400, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.checkCollision.up = false; - // sprite.body.checkCollision.right = false; - - sprite2 = game.add.sprite(330, 100, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch9, this); - -} - -function launch9() { - - sprite2.body.velocity.y = 100; - -} - -function test8() { - - game.physics.gravity.y = 150; - - sprite = game.add.sprite(300, 400, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.checkCollision.left = false; - sprite.body.checkCollision.right = false; - - sprite2 = game.add.sprite(500, 400, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch8, this); - -} - -function launch8() { - - sprite.body.velocity.x = -50; - sprite2.body.velocity.x = -200; - -} - - - -function test7() { - - game.physics.gravity.y = 200; - - sprite = game.add.sprite(0, 300, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - // sprite.body.velocity.y = 100; - - // sprite.body.gravity.y = 200; - - // sprite.body.linearDamping = 0.2; - - game.input.onDown.add(launch7, this); - -} - -function launch7() { - - sprite.body.velocity.x = -200; - sprite.body.velocity.y = 200; - -} - - - - -function test6() { - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(300, 200, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.5, 0.5); - - game.input.onDown.add(launch6, this); - -} - -function launch6() { - - sprite.body.velocity.x = 200; - sprite.body.velocity.y = -200; - -} - - - - -function test5() { - - sprite = game.add.sprite(0, 600, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - // sprite.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch5, this); - -} - -function launch5() { - - sprite.body.velocity.x = 100; - sprite.body.velocity.y = -100; - game.time.events.add(Phaser.Timer.SECOND * 4, stop5, this); - -} - -function stop5() { - - sprite.body.velocity.x = -100; - // sprite.body.velocity.y = 100; - console.log(sprite.x, sprite.body.x); - -} - - - - - - - -function test4() { - - game.physics.gravity.y = 150; - - sprite = game.add.sprite(300, 0, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.9, 0.9); - - sprite2 = game.add.sprite(310, 500, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - // sprite2.body.bounce.setTo(0.9, 0.9); - - game.input.onDown.add(launch4, this); - -} - -function launch4() { - - sprite.body.velocity.y = 200; - -} - -function test3() { - - game.physics.gravity.y = 50; - - // group = game.add.group(); - - sprite = game.add.sprite(500, 400, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.9, 0.9); - - sprite2 = game.add.sprite(100, 400, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - - // sprite2.body.immovable = true; - // sprite2.body.bounce.setTo(0.5, 0.5); - - sprite3 = game.add.sprite(700, 400, 'gameboy', 3); - sprite3.name = 'yellow'; - sprite3.body.collideWorldBounds = true; - sprite3.body.bounce.setTo(0.5, 0.5); - - // sprite.body.velocity.x = -300; - // sprite.body.velocity.y = -200; - - // group.add(sprite); - // group.add(sprite2); - // group.add(sprite3); - - game.input.onDown.add(launch3, this); - -} - -function launch3() { - - sprite.body.velocity.x = -200; - sprite.body.velocity.y = -200; - -} - -function test2() { - - // game.physics.gravity.y = 100; - - sprite = game.add.sprite(700, 400, 'ball'); - sprite.name = 'sprite1'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - sprite2 = game.add.sprite(100, 400, 'ball'); - sprite2.name = 'sprite2'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - sprite2.body.immovable = true; - - // sprite.body.velocity.x = -225; - // sprite2.body.velocity.x = 225; - - - game.input.onDown.addOnce(launch2, this); - -} - -function launch2() { - - sprite.body.velocity.x = -225; - sprite2.body.velocity.x = 225; - -} - -function test1() { - - // game.physics.gravity.y = 100; - - sprite = game.add.sprite(100, 400, 'ball'); - sprite.name = 'sprite1'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - sprite2 = game.add.sprite(700, 400, 'ball'); - sprite2.name = 'sprite2'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - game.input.onDown.add(launch1, this); - -} - -function launch1() { - - sprite.body.velocity.x = 225; - // sprite2.body.velocity.x = -225; - -} - -function update() { - - // game.physics.collide(group, group); - - if (sprite3) - { - game.physics.collide(sprite, [sprite2, sprite3]); - game.physics.collide(sprite2, sprite3); - } - else - { - game.physics.collide(sprite, sprite2); - } - - - if (sprite) - { - bmd.fillStyle('#ffff00'); - bmd.fillRect(sprite.body.center.x, sprite.body.center.y, 2, 2); - } - - if (sprite2) - { - bmd.fillStyle('#ff00ff'); - bmd.fillRect(sprite2.body.center.x, sprite2.body.center.y, 2, 2); - } - - if (sprite3) - { - bmd.fillStyle('#0000ff'); - bmd.fillRect(sprite3.body.center.x, sprite3.body.center.y, 2, 2); - } - -} - -function render() { - - if (sprite) - { - game.debug.bodyInfo(sprite2, 16, 24); - // game.debug.text(sprite.name + ' x: ' + sprite.x.toFixed(2) + ' dx: ' + sprite.body._dx.toFixed(2), 16, 500); - // game.debug.text(sprite.name + ' y: ' + sprite.y.toFixed(2) + ' dy: ' + sprite.body._dy.toFixed(2), 16, 520); - } - - if (sprite2) - { - // game.debug.bodyInfo(sprite2, 16, 190); - // game.debug.text(sprite2.name + ' x: ' + sprite2.x, 400, 500); - } - -} diff --git a/examples/wip/misc/64x64.png b/examples/wip/misc/64x64.png deleted file mode 100644 index f839a2ee0..000000000 Binary files a/examples/wip/misc/64x64.png and /dev/null differ diff --git a/examples/wip/misc/SAT.js b/examples/wip/misc/SAT.js deleted file mode 100644 index 63570ecec..000000000 --- a/examples/wip/misc/SAT.js +++ /dev/null @@ -1,862 +0,0 @@ -// Version 0.2 - Copyright 2013 - Jim Riecken -// -// Released under the MIT License - https://github.com/jriecken/sat-js -// -// A simple library for determining intersections of circles and -// polygons using the Separating Axis Theorem. -/** @preserve SAT.js - Version 0.2 - Copyright 2013 - Jim Riecken - released under the MIT License. https://github.com/jriecken/sat-js */ - -/*global define: false, module: false*/ -/*jshint shadow:true, sub:true, forin:true, noarg:true, noempty:true, - eqeqeq:true, bitwise:true, strict:true, undef:true, - curly:true, browser:true */ - -// Create a UMD wrapper for SAT. Works in: -// -// - Plain browser via global SAT variable -// - AMD loader (like require.js) -// - Node.js -// -// The quoted properties all over the place are used so that the Closure Compiler -// does not mangle the exposed API in advanced mode. -/** - * @param {*} root - The global scope - * @param {Function} factory - Factory that creates SAT module - */ -(function (root, factory) { - "use strict"; - if (typeof define === 'function' && define['amd']) { - define(factory); - } else if (typeof exports === 'object') { - module['exports'] = factory(); - } else { - root['SAT'] = factory(); - } -}(this, function () { - "use strict"; - - var SAT = {}; - - // - // ## Vector - // - // Represents a vector in two dimensions with `x` and `y` properties. - - - // Create a new Vector, optionally passing in the `x` and `y` coordinates. If - // a coordinate is not specified, it will be set to `0` - /** - * @param {?number=} x The x position. - * @param {?number=} y The y position. - * @constructor - */ - function Vector(x, y) { - this['x'] = x || 0; - this['y'] = y || 0; - } - SAT['Vector'] = Vector; - // Alias `Vector` as `V` - SAT['V'] = Vector; - - - // Copy the values of another Vector into this one. - /** - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - Vector.prototype['copy'] = Vector.prototype.copy = function(other) { - this['x'] = other['x']; - this['y'] = other['y']; - return this; - }; - - // Change this vector to be perpendicular to what it was before. (Effectively - // roatates it 90 degrees in a clockwise direction) - /** - * @return {Vector} This for chaining. - */ - Vector.prototype['perp'] = Vector.prototype.perp = function() { - var x = this['x']; - this['x'] = this['y']; - this['y'] = -x; - return this; - }; - - // Rotate this vector (counter-clockwise) by the specified angle (in radians). - /** - * @param {number} angle The angle to rotate (in radians) - * @return {Vector} This for chaining. - */ - Vector.prototype['rotate'] = Vector.prototype.rotate = function (angle) { - var x = this['x']; - var y = this['y']; - this['x'] = x * Math.cos(angle) - y * Math.sin(angle); - this['y'] = x * Math.sin(angle) + y * Math.cos(angle); - return this; - }; - - // Rotate this vector (counter-clockwise) by the specified angle (in radians) which has already been calculated into sin and cos. - /** - * @param {number} sin - The Math.sin(angle) - * @param {number} cos - The Math.cos(angle) - * @return {Vector} This for chaining. - */ - Vector.prototype['rotatePrecalc'] = Vector.prototype.rotatePrecalc = function (sin, cos) { - var x = this['x']; - var y = this['y']; - this['x'] = x * cos - y * sin; - this['y'] = x * sin + y * cos; - return this; - }; - - // Reverse this vector. - /** - * @return {Vector} This for chaining. - */ - Vector.prototype['reverse'] = Vector.prototype.reverse = function() { - this['x'] = -this['x']; - this['y'] = -this['y']; - return this; - }; - - - // Normalize this vector. (make it have length of `1`) - /** - * @return {Vector} This for chaining. - */ - Vector.prototype['normalize'] = Vector.prototype.normalize = function() { - var d = this.len(); - if(d > 0) { - this['x'] = this['x'] / d; - this['y'] = this['y'] / d; - } - return this; - }; - - // Add another vector to this one. - /** - * @param {Vector} other The other Vector. - * @return {Vector} This for chaining. - */ - Vector.prototype['add'] = Vector.prototype.add = function(other) { - this['x'] += other['x']; - this['y'] += other['y']; - return this; - }; - - // Subtract another vector from this one. - /** - * @param {Vector} other The other Vector. - * @return {Vector} This for chaiing. - */ - Vector.prototype['sub'] = Vector.prototype.sub = function(other) { - this['x'] -= other['x']; - this['y'] -= other['y']; - return this; - }; - - // Scale this vector. An independant scaling factor can be provided - // for each axis, or a single scaling factor that will scale both `x` and `y`. - /** - * @param {number} x The scaling factor in the x direction. - * @param {?number=} y The scaling factor in the y direction. If this - * is not specified, the x scaling factor will be used. - * @return {Vector} This for chaining. - */ - Vector.prototype['scale'] = Vector.prototype.scale = function(x,y) { - this['x'] *= x; - this['y'] *= y || x; - return this; - }; - - // Project this vector on to another vector. - /** - * @param {Vector} other The vector to project onto. - * @return {Vector} This for chaining. - */ - Vector.prototype['project'] = Vector.prototype.project = function(other) { - var amt = this.dot(other) / other.len2(); - this['x'] = amt * other['x']; - this['y'] = amt * other['y']; - return this; - }; - - // Project this vector onto a vector of unit length. This is slightly more efficient - // than `project` when dealing with unit vectors. - /** - * @param {Vector} other The unit vector to project onto. - * @return {Vector} This for chaining. - */ - Vector.prototype['projectN'] = Vector.prototype.projectN = function(other) { - var amt = this.dot(other); - this['x'] = amt * other['x']; - this['y'] = amt * other['y']; - return this; - }; - - // Reflect this vector on an arbitrary axis. - /** - * @param {Vector} axis The vector representing the axis. - * @return {Vector} This for chaining. - */ - Vector.prototype['reflect'] = Vector.prototype.reflect = function(axis) { - var x = this['x']; - var y = this['y']; - this.project(axis).scale(2); - this['x'] -= x; - this['y'] -= y; - return this; - }; - - // Reflect this vector on an arbitrary axis (represented by a unit vector). This is - // slightly more efficient than `reflect` when dealing with an axis that is a unit vector. - /** - * @param {Vector} axis The unit vector representing the axis. - * @return {Vector} This for chaining. - */ - Vector.prototype['reflectN'] = Vector.prototype.reflectN = function(axis) { - var x = this['x']; - var y = this['y']; - this.projectN(axis).scale(2); - this['x'] -= x; - this['y'] -= y; - return this; - }; - - // Get the dot product of this vector and another. - /** - * @param {Vector} other The vector to dot this one against. - * @return {number} The dot product. - */ - Vector.prototype['dot'] = Vector.prototype.dot = function(other) { - return this['x'] * other['x'] + this['y'] * other['y']; - }; - - // Get the squared length of this vector. - /** - * @return {number} The length^2 of this vector. - */ - Vector.prototype['len2'] = Vector.prototype.len2 = function() { - return this.dot(this); - }; - - // Get the length of this vector. - /** - * @return {number} The length of this vector. - */ - Vector.prototype['len'] = Vector.prototype.len = function() { - return Math.sqrt(this.len2()); - }; - - // ## Circle - // - // Represents a circle with a position and a radius. - - // Create a new circle, optionally passing in a position and/or radius. If no position - // is given, the circle will be at `(0,0)`. If no radius is provided, the circle will - // have a radius of `0`. - /** - * @param {Vector=} pos A vector representing the position of the center of the circle - * @param {?number=} r The radius of the circle - * @constructor - */ - function Circle(pos, r) { - this['pos'] = pos || new Vector(); - this['r'] = r || 0; - } - SAT['Circle'] = Circle; - - // ## Polygon - // - // Represents a *convex* polygon with any number of points (specified in counter-clockwise order) - // - // The edges/normals of the polygon will be calculated on creation and stored in the - // `edges` and `normals` properties. If you change the polygon's points, you will need - // to call `recalc` to recalculate the edges/normals. - - // Create a new polygon, passing in a position vector, and an array of points (represented - // by vectors relative to the position vector). If no position is passed in, the position - // of the polygon will be `(0,0)`. - /** - * @param {Vector=} pos A vector representing the origin of the polygon. (all other - * points are relative to this one) - * @param {Array.=} points An array of vectors representing the points in the polygon, - * in counter-clockwise order. - * @constructor - */ - function Polygon(pos, points) { - this['pos'] = pos || new Vector(); - this['points'] = points || []; - this.recalc(); - } - SAT['Polygon'] = Polygon; - - // Recalculates the edges and normals of the polygon. This **must** be called - // if the `points` array is modified at all and the edges or normals are to be - // accessed. - /** - * @return {Polygon} This for chaining. - */ - Polygon.prototype['recalc'] = Polygon.prototype.recalc = function() { - // The edges here are the direction of the `n`th edge of the polygon, relative to - // the `n`th point. If you want to draw a given edge from the edge value, you must - // first translate to the position of the starting point. - this['edges'] = []; - // The normals here are the direction of the normal for the `n`th edge of the polygon, relative - // to the position of the `n`th point. If you want to draw an edge normal, you must first - // translate to the position of the starting point. - this['normals'] = []; - var points = this['points']; - var len = points.length; - for (var i = 0; i < len; i++) { - var p1 = points[i]; - var p2 = i < len - 1 ? points[i + 1] : points[0]; - var e = new Vector().copy(p2).sub(p1); - var n = new Vector().copy(e).perp().normalize(); - this['edges'].push(e); - this['normals'].push(n); - } - return this; - }; - - // Rotates this polygon counter-clockwise around the origin of *its local coordinate system* (i.e. `pos`). - // - // Note: You do **not** need to call `recalc` after rotation. - /** - * @param {number} angle The angle to rotate (in radians) - * @return {Polygon} This for chaining. - */ - Polygon.prototype['rotate'] = Polygon.prototype.rotate = function(angle) { - var i; - var points = this['points']; - var edges = this['edges']; - var normals = this['normals']; - var len = points.length; - - // Calc it just the once, rather than 4 times per array element - var cos = Math.cos(angle); - var sin = Math.sin(angle); - - for (i = 0; i < len; i++) { - points[i].rotatePrecalc(sin, cos); - edges[i].rotatePrecalc(sin, cos); - normals[i].rotatePrecalc(sin, cos); - } - return this; - }; - - // Rotates this polygon counter-clockwise around the origin of *its local coordinate system* (i.e. `pos`). - // - // Note: You do **not** need to call `recalc` after rotation. - /** - * @param {number} angle The angle to rotate (in radians) - * @return {Polygon} This for chaining. - */ - Polygon.prototype['scale'] = Polygon.prototype.scale = function(x, y) { - var i; - var points = this['points']; - var edges = this['edges']; - var normals = this['normals']; - var len = points.length; - for (i = 0; i < len; i++) { - points[i].scale(x,y); - edges[i].scale(x,y); - normals[i].scale(x,y); - } - return this; - }; - - // Translates the points of this polygon by a specified amount relative to the origin of *its own coordinate - // system* (i.e. `pos`). - // - // This is most useful to change the "center point" of a polygon. - // - // Note: You do **not** need to call `recalc` after translation. - /** - * @param {number} x The horizontal amount to translate. - * @param {number} y The vertical amount to translate. - * @return {Polygon} This for chaining. - */ - Polygon.prototype['translate'] = Polygon.prototype.translate = function (x, y) { - var i; - var points = this['points']; - var len = points.length; - for (i = 0; i < len; i++) { - points[i].x += x; - points[i].y += y; - } - return this; - }; - - // ## Box - // - // Represents an axis-aligned box, with a width and height. - - - // Create a new box, with the specified position, width, and height. If no position - // is given, the position will be `(0,0)`. If no width or height are given, they will - // be set to `0`. - /** - * @param {Vector=} pos A vector representing the top-left of the box. - * @param {?number=} w The width of the box. - * @param {?number=} h The height of the box. - * @constructor - */ - function Box(pos, w, h) { - this['pos'] = pos || new Vector(); - this['w'] = w || 0; - this['h'] = h || 0; - } - SAT['Box'] = Box; - - // Returns a polygon whose edges are the same as this box. - /** - * @return {Polygon} A new Polygon that represents this box. - */ - Box.prototype['toPolygon'] = Box.prototype.toPolygon = function() { - var pos = this['pos']; - var w = this['w']; - var h = this['h']; - return new Polygon(new Vector(pos['x'], pos['y']), [ - new Vector(), new Vector(w, 0), - new Vector(w,h), new Vector(0,h) - ]); - }; - - // ## Response - // - // An object representing the result of an intersection. Contains: - // - The two objects participating in the intersection - // - The vector representing the minimum change necessary to extract the first object - // from the second one (as well as a unit vector in that direction and the magnitude - // of the overlap) - // - Whether the first object is entirely inside the second, and vice versa. - /** - * @constructor - */ - function Response() { - this['a'] = null; - this['b'] = null; - this['overlapN'] = new Vector(); - this['overlapV'] = new Vector(); - this.clear(); - } - SAT['Response'] = Response; - - // Set some values of the response back to their defaults. Call this between tests if - // you are going to reuse a single Response object for multiple intersection tests (recommented - // as it will avoid allcating extra memory) - /** - * @return {Response} This for chaining - */ - Response.prototype['clear'] = Response.prototype.clear = function() { - this['aInB'] = true; - this['bInA'] = true; - this['overlap'] = Number.MAX_VALUE; - return this; - }; - - // ## Object Pools - - // A pool of `Vector` objects that are used in calculations to avoid - // allocating memory. - /** - * @type {Array.} - */ - var T_VECTORS = []; - for (var i = 0; i < 10; i++) { T_VECTORS.push(new Vector()); } - - // A pool of arrays of numbers used in calculations to avoid allocating - // memory. - /** - * @type {Array.>} - */ - var T_ARRAYS = []; - for (var i = 0; i < 5; i++) { T_ARRAYS.push([]); } - - // ## Helper Functions - - // Flattens the specified array of points onto a unit vector axis, - // resulting in a one dimensional range of the minimum and - // maximum value on that axis. - /** - * @param {Array.} points The points to flatten. - * @param {Vector} normal The unit vector axis to flatten on. - * @param {Array.} result An array. After calling this function, - * result[0] will be the minimum value, - * result[1] will be the maximum value. - */ - function flattenPointsOn(points, normal, result) { - var min = Number.MAX_VALUE; - var max = -Number.MAX_VALUE; - var len = points.length; - for (var i = 0; i < len; i++ ) { - // The magnitude of the projection of the point onto the normal - var dot = points[i].dot(normal); - if (dot < min) { min = dot; } - if (dot > max) { max = dot; } - } - result[0] = min; result[1] = max; - } - - // Check whether two convex polygons are separated by the specified - // axis (must be a unit vector). - /** - * @param {Vector} aPos The position of the first polygon. - * @param {Vector} bPos The position of the second polygon. - * @param {Array.} aPoints The points in the first polygon. - * @param {Array.} bPoints The points in the second polygon. - * @param {Vector} axis The axis (unit sized) to test against. The points of both polygons - * will be projected onto this axis. - * @param {Response=} response A Response object (optional) which will be populated - * if the axis is not a separating axis. - * @return {boolean} true if it is a separating axis, false otherwise. If false, - * and a response is passed in, information about how much overlap and - * the direction of the overlap will be populated. - */ - function isSeparatingAxis(aPos, bPos, aPoints, bPoints, axis, response) { - var rangeA = T_ARRAYS.pop(); - var rangeB = T_ARRAYS.pop(); - // The magnitude of the offset between the two polygons - var offsetV = T_VECTORS.pop().copy(bPos).sub(aPos); - var projectedOffset = offsetV.dot(axis); - // Project the polygons onto the axis. - flattenPointsOn(aPoints, axis, rangeA); - flattenPointsOn(bPoints, axis, rangeB); - // Move B's range to its position relative to A. - rangeB[0] += projectedOffset; - rangeB[1] += projectedOffset; - // Check if there is a gap. If there is, this is a separating axis and we can stop - if (rangeA[0] > rangeB[1] || rangeB[0] > rangeA[1]) { - T_VECTORS.push(offsetV); - T_ARRAYS.push(rangeA); - T_ARRAYS.push(rangeB); - return true; - } - // This is not a separating axis. If we're calculating a response, calculate the overlap. - if (response) { - var overlap = 0; - // A starts further left than B - if (rangeA[0] < rangeB[0]) { - response['aInB'] = false; - // A ends before B does. We have to pull A out of B - if (rangeA[1] < rangeB[1]) { - overlap = rangeA[1] - rangeB[0]; - response['bInA'] = false; - // B is fully inside A. Pick the shortest way out. - } else { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - // B starts further left than A - } else { - response['bInA'] = false; - // B ends before A ends. We have to push A out of B - if (rangeA[1] > rangeB[1]) { - overlap = rangeA[0] - rangeB[1]; - response['aInB'] = false; - // A is fully inside B. Pick the shortest way out. - } else { - var option1 = rangeA[1] - rangeB[0]; - var option2 = rangeB[1] - rangeA[0]; - overlap = option1 < option2 ? option1 : -option2; - } - } - // If this is the smallest amount of overlap we've seen so far, set it as the minimum overlap. - var absOverlap = Math.abs(overlap); - if (absOverlap < response['overlap']) { - response['overlap'] = absOverlap; - response['overlapN'].copy(axis); - if (overlap < 0) { - response['overlapN'].reverse(); - } - } - } - T_VECTORS.push(offsetV); - T_ARRAYS.push(rangeA); - T_ARRAYS.push(rangeB); - return false; - } - - // Calculates which Vornoi region a point is on a line segment. - // It is assumed that both the line and the point are relative to `(0,0)` - // - // | (0) | - // (-1) [S]--------------[E] (1) - // | (0) | - /** - * @param {Vector} line The line segment. - * @param {Vector} point The point. - * @return {number} LEFT_VORNOI_REGION (-1) if it is the left region, - * MIDDLE_VORNOI_REGION (0) if it is the middle region, - * RIGHT_VORNOI_REGION (1) if it is the right region. - */ - function vornoiRegion(line, point) { - var len2 = line.len2(); - var dp = point.dot(line); - // If the point is beyond the start of the line, it is in the - // left vornoi region. - if (dp < 0) { return LEFT_VORNOI_REGION; } - // If the point is beyond the end of the line, it is in the - // right vornoi region. - else if (dp > len2) { return RIGHT_VORNOI_REGION; } - // Otherwise, it's in the middle one. - else { return MIDDLE_VORNOI_REGION; } - } - // Constants for Vornoi regions - /** - * @const - */ - var LEFT_VORNOI_REGION = -1; - /** - * @const - */ - var MIDDLE_VORNOI_REGION = 0; - /** - * @const - */ - var RIGHT_VORNOI_REGION = 1; - - // ## Collision Tests - - // Check if two circles collide. - /** - * @param {Circle} a The first circle. - * @param {Circle} b The second circle. - * @param {Response=} response Response object (optional) that will be populated if - * the circles intersect. - * @return {boolean} true if the circles intersect, false if they don't. - */ - function testCircleCircle(a, b, response) { - // Check if the distance between the centers of the two - // circles is greater than their combined radius. - var differenceV = T_VECTORS.pop().copy(b['pos']).sub(a['pos']); - var totalRadius = a['r'] + b['r']; - var totalRadiusSq = totalRadius * totalRadius; - var distanceSq = differenceV.len2(); - // If the distance is bigger than the combined radius, they don't intersect. - if (distanceSq > totalRadiusSq) { - T_VECTORS.push(differenceV); - return false; - } - // They intersect. If we're calculating a response, calculate the overlap. - if (response) { - var dist = Math.sqrt(distanceSq); - response['a'] = a; - response['b'] = b; - response['overlap'] = totalRadius - dist; - response['overlapN'].copy(differenceV.normalize()); - response['overlapV'].copy(differenceV).scale(response['overlap']); - response['aInB']= a['r'] <= b['r'] && dist <= b['r'] - a['r']; - response['bInA'] = b['r'] <= a['r'] && dist <= a['r'] - b['r']; - } - T_VECTORS.push(differenceV); - return true; - } - SAT['testCircleCircle'] = testCircleCircle; - - // Check if a polygon and a circle collide. - /** - * @param {Polygon} polygon The polygon. - * @param {Circle} circle The circle. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testPolygonCircle(polygon, circle, response) { - // Get the position of the circle relative to the polygon. - var circlePos = T_VECTORS.pop().copy(circle['pos']).sub(polygon['pos']); - var radius = circle['r']; - var radius2 = radius * radius; - var points = polygon['points']; - var len = points.length; - var edge = T_VECTORS.pop(); - var point = T_VECTORS.pop(); - - // For each edge in the polygon: - for (var i = 0; i < len; i++) { - var next = i === len - 1 ? 0 : i + 1; - var prev = i === 0 ? len - 1 : i - 1; - var overlap = 0; - var overlapN = null; - - // Get the edge. - edge.copy(polygon['edges'][i]); - // Calculate the center of the circle relative to the starting point of the edge. - point.copy(circlePos).sub(points[i]); - - // If the distance between the center of the circle and the point - // is bigger than the radius, the polygon is definitely not fully in - // the circle. - if (response && point.len2() > radius2) { - response['aInB'] = false; - } - - // Calculate which Vornoi region the center of the circle is in. - var region = vornoiRegion(edge, point); - // If it's the left region: - if (region === LEFT_VORNOI_REGION) { - // We need to make sure we're in the RIGHT_VORNOI_REGION of the previous edge. - edge.copy(polygon['edges'][prev]); - // Calculate the center of the circle relative the starting point of the previous edge - var point2 = T_VECTORS.pop().copy(circlePos).sub(points[prev]); - region = vornoiRegion(edge, point2); - if (region === RIGHT_VORNOI_REGION) { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.len(); - if (dist > radius) { - // No intersection - T_VECTORS.push(circlePos); - T_VECTORS.push(edge); - T_VECTORS.push(point); - T_VECTORS.push(point2); - return false; - } else if (response) { - // It intersects, calculate the overlap. - response['bInA'] = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - T_VECTORS.push(point2); - // If it's the right region: - } else if (region === RIGHT_VORNOI_REGION) { - // We need to make sure we're in the left region on the next edge - edge.copy(polygon['edges'][next]); - // Calculate the center of the circle relative to the starting point of the next edge. - point.copy(circlePos).sub(points[next]); - region = vornoiRegion(edge, point); - if (region === LEFT_VORNOI_REGION) { - // It's in the region we want. Check if the circle intersects the point. - var dist = point.len(); - if (dist > radius) { - // No intersection - T_VECTORS.push(circlePos); - T_VECTORS.push(edge); - T_VECTORS.push(point); - return false; - } else if (response) { - // It intersects, calculate the overlap. - response['bInA'] = false; - overlapN = point.normalize(); - overlap = radius - dist; - } - } - // Otherwise, it's the middle region: - } else { - // Need to check if the circle is intersecting the edge, - // Change the edge into its "edge normal". - var normal = edge.perp().normalize(); - // Find the perpendicular distance between the center of the - // circle and the edge. - var dist = point.dot(normal); - var distAbs = Math.abs(dist); - // If the circle is on the outside of the edge, there is no intersection. - if (dist > 0 && distAbs > radius) { - // No intersection - T_VECTORS.push(circlePos); - T_VECTORS.push(normal); - T_VECTORS.push(point); - return false; - } else if (response) { - // It intersects, calculate the overlap. - overlapN = normal; - overlap = radius - dist; - // If the center of the circle is on the outside of the edge, or part of the - // circle is on the outside, the circle is not fully inside the polygon. - if (dist >= 0 || overlap < 2 * radius) { - response['bInA'] = false; - } - } - } - - // If this is the smallest overlap we've seen, keep it. - // (overlapN may be null if the circle was in the wrong Vornoi region). - if (overlapN && response && Math.abs(overlap) < Math.abs(response['overlap'])) { - response['overlap'] = overlap; - response['overlapN'].copy(overlapN); - } - } - - // Calculate the final overlap vector - based on the smallest overlap. - if (response) { - response['a'] = polygon; - response['b'] = circle; - response['overlapV'].copy(response['overlapN']).scale(response['overlap']); - } - T_VECTORS.push(circlePos); - T_VECTORS.push(edge); - T_VECTORS.push(point); - return true; - } - SAT['testPolygonCircle'] = testPolygonCircle; - - // Check if a circle and a polygon collide. - // - // **NOTE:** This is slightly less efficient than polygonCircle as it just - // runs polygonCircle and reverses everything at the end. - /** - * @param {Circle} circle The circle. - * @param {Polygon} polygon The polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testCirclePolygon(circle, polygon, response) { - // Test the polygon against the circle. - var result = testPolygonCircle(polygon, circle, response); - if (result && response) { - // Swap A and B in the response. - var a = response['a']; - var aInB = response['aInB']; - response['overlapN'].reverse(); - response['overlapV'].reverse(); - response['a'] = response['b']; - response['b'] = a; - response['aInB'] = response['bInA']; - response['bInA'] = aInB; - } - return result; - } - SAT['testCirclePolygon'] = testCirclePolygon; - - // Checks whether polygons collide. - /** - * @param {Polygon} a The first polygon. - * @param {Polygon} b The second polygon. - * @param {Response=} response Response object (optional) that will be populated if - * they interset. - * @return {boolean} true if they intersect, false if they don't. - */ - function testPolygonPolygon(a, b, response) { - var aPoints = a['points']; - var aLen = aPoints.length; - var bPoints = b['points']; - var bLen = bPoints.length; - // If any of the edge normals of A is a separating axis, no intersection. - for (var i = 0; i < aLen; i++) { - if (isSeparatingAxis(a['pos'], b['pos'], aPoints, bPoints, a['normals'][i], response)) { - return false; - } - } - // If any of the edge normals of B is a separating axis, no intersection. - for (var i = 0;i < bLen; i++) { - if (isSeparatingAxis(a['pos'], b['pos'], aPoints, bPoints, b['normals'][i], response)) { - return false; - } - } - // Since none of the edge normals of A or B are a separating axis, there is an intersection - // and we've already calculated the smallest overlap (in isSeparatingAxis). Calculate the - // final overlap vector. - if (response) { - response['a'] = a; - response['b'] = b; - response['overlapV'].copy(response['overlapN']).scale(response['overlap']); - } - return true; - } - SAT['testPolygonPolygon'] = testPolygonPolygon; - - return SAT; -})); \ No newline at end of file diff --git a/examples/wip/misc/acceleration.js b/examples/wip/misc/acceleration.js deleted file mode 100644 index 8673ae87a..000000000 --- a/examples/wip/misc/acceleration.js +++ /dev/null @@ -1,100 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('car', 'assets/sprites/car90.png'); - game.load.image('baddie', 'assets/sprites/space-baddie.png'); - -} - -var car; -var aliens; - -function create() { - - // aliens = game.add.group(); - - // for (var i = 0; i < 50; i++) - // { - // var s = aliens.create(game.world.randomX, game.world.randomY, 'baddie'); - // s.name = 'alien' + s; - // s.body.collideWorldBounds = true; - // s.body.bounce.setTo(0.8, 0.8); - // s.body.velocity.setTo(10 + Math.random() * 40, 10 + Math.random() * 40); - // } - - car = game.add.sprite(0, 300, 'car'); - car.anchor.setTo(0.5, 0.5); - car.body.collideWorldBounds = true; - car.body.bounce.setTo(0.8, 0.8); - car.body.allowRotation = true; - car.body.linearDamping = 0.4; - - // car.body.acceleration.x = 10; - game.input.onDown.add(start, this); - -} - -var s = 0; - -function start() { - - // car.body.velocity.x = 200; - car.body.acceleration.x = 100; - s = game.time.now; - -} - -function update() { - - // if (car.x >= 400 && car.body.velocity.x > 0) - // { - // car.body.velocity.x = 0; - // car.body.acceleration.x = 0; - // var total = game.time.now - s; - // console.log(game.time.physicsElapsed); - // console.log('total ms', total, 'px/sec', car.x/(total/1000)); - // } - - // car.body.velocity.x = 0; - // car.body.velocity.y = 0; - car.body.angularVelocity = 0; - - car.body.acceleration.x = 0; - car.body.acceleration.y = 0; - - if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - car.body.angularVelocity = -200; - // car.body.acceleration.x = -100; - } - else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - car.body.angularVelocity = 200; - // car.body.acceleration.x = 100; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - game.physics.accelerationFromRotation(car.rotation, 400, car.body.acceleration); - - // car.body.acceleration.x = 10; - // car.body.acceleration.copyFrom(game.physics.velocityFromAngle(car.angle, 30)); - // car.body.velocity.copyFrom(game.physics.velocityFromAngle(car.angle, 300)); - } - else - { - // game.physics.accelerationFromRotation(car.rotation, 10, car.body.acceleration); - } - - // game.physics.collide(car, aliens); - -} - -function render() { - - // game.debug.spriteInfo(car, 32, 32); - game.debug.bodyInfo(car, 16, 24); - -} diff --git a/examples/wip/misc/audio loop.js b/examples/wip/misc/audio loop.js deleted file mode 100644 index bf012041a..000000000 --- a/examples/wip/misc/audio loop.js +++ /dev/null @@ -1,46 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.audio('music', 'assets/audio/CatAstroPhi_shmup_normal.wav'); - -} - -var music; - -function create() { - - music = game.add.audio('music'); - - // play: function (marker, position, volume, loop, forceRestart) { - - music.play('', 0, 1, true); - - game.input.onDown.add(toggleAudio, this); - -} - -function toggleAudio() { - - if (music.isPlaying) - { - music.pause(); - } - else - { - music.resume(); - } - -} - -function update() { - - -} - -function render() { - - game.debug.soundInfo(music, 32, 32); - -} diff --git a/examples/wip/misc/blocked.js b/examples/wip/misc/blocked.js deleted file mode 100644 index 45192a2d5..000000000 --- a/examples/wip/misc/blocked.js +++ /dev/null @@ -1,281 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('chunk', 'assets/sprites/chunk.png'); - game.load.image('arrow', 'assets/sprites/asteroids_ship.png'); - game.load.image('p', 'assets/sprites/mushroom2.png'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -var sprite; -var sprite2; - -var track; -var bmd; - -function create() { - - game.stage.backgroundColor = '#124184'; - - bmd = game.add.bitmapData(800, 600); - bmd.fillStyle('#ffffff'); - var bg = game.add.sprite(0, 0, bmd); - bg.body.moves = false; - - test9(); - -} - -// stacked -function test9() { - - game.physics.gravity.y = 500; - - sprite = game.add.sprite(400, 100, 'ball'); - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - sprite.body.minBounceVelocity = 0.8; - - sprite2 = game.add.sprite(400, 300, 'ball'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.5, 0.5); - sprite2.body.minBounceVelocity = 0.8; - - // game.input.onDown.add(launch8, this); - -} - -// gravity into floor jiggle -function test8() { - - game.physics.gravity.y = 1000; - - sprite = game.add.sprite(400, 100, 'ball'); - sprite.body.collideWorldBounds = true; - // it's all about tweaking these values - sprite.body.bounce.setTo(0.8, 0.8); - sprite.body.minBounceVelocity = 1.2; - sprite.body.velocity.x = -400; - sprite.body.linearDamping = 1.2; - - sprite2 = game.add.sprite(500, 100, 'ball'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.5, 0.5); - sprite2.body.minBounceVelocity = 0.8; - sprite2.body.linearDamping = 0.5; - - game.input.onDown.add(launch8, this); - -} - -function launch8() { - - // sprite.body.velocity.x = -200; - sprite2.body.velocity.x = 200; - -} - -// both sprites are shot into each other vertically -function test7() { - - // game.physics.gravity.y = 50; - - sprite = game.add.sprite(400, 600, 'ball'); - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - sprite2 = game.add.sprite(400, 100, 'ball'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - - game.input.onDown.add(launch7, this); - -} - -function launch7() { - - sprite.body.velocity.y = -200; - // sprite2.body.velocity.y = 200; - -} - - -// sprite is on the bottom, blocked by the world bounds, sprite2 falls onto it via gravity only -function test6() { - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(380, 600, 'p'); - sprite.body.collideWorldBounds = true; - - sprite2 = game.add.sprite(400, 100, 'ball'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - -} - -// sprite is on the bottom, blocked by the world bounds, sprite2 falls onto it -function test5() { - - game.physics.gravity.y = 50; - - sprite = game.add.sprite(400, 600, 'ball'); - sprite.body.collideWorldBounds = true; - - sprite2 = game.add.sprite(400, 100, 'ball'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - - game.input.onDown.add(launch5, this); - -} - -function launch5() { - - sprite2.body.velocity.y = 200; - -} - - -// bounce both sprites into each other, one with lots less velocity - checking newtons craddle approach -function test4() { - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(780, 400, 'ball'); - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - sprite2 = game.add.sprite(0, 400, 'ball'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - - game.input.onDown.add(launch4, this); - -} - -function launch4() { - - sprite.body.velocity.x = 70; - sprite2.body.velocity.x = -250; - -} - -// bounce both sprites into each other, identical bounce + velocity -function test3() { - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(780, 400, 'p'); - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - sprite2 = game.add.sprite(0, 400, 'p'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - - game.input.onDown.add(launch3, this); - -} - -function launch3() { - - sprite.body.velocity.x = 225; - sprite2.body.velocity.x = -225; - -} - -// sprite is on the right, blocked by the world bounds, sprite2 bounces into it -function test2() { - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(780, 400, 'p'); - sprite.body.collideWorldBounds = true; - - sprite2 = game.add.sprite(0, 400, 'p'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - - game.input.onDown.add(launch2, this); - -} - -function launch2() { - - sprite2.body.velocity.x = -225; - -} - -// sprite is on the left, blocked by the world bounds, sprite2 bounces into it -function test1() { - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(0, 400, 'p'); - sprite.body.collideWorldBounds = true; - - sprite2 = game.add.sprite(700, 400, 'p'); - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.8, 0.8); - - track = sprite2; - - game.input.onDown.add(launch1, this); - -} - -function launch1() { - - sprite2.body.velocity.x = -225; - -} - -function update() { - - game.physics.collide(sprite, sprite2); - - // sprite.rotation = sprite.body.angle; - - if (sprite) - { - bmd.fillStyle('#ffff00'); - bmd.fillRect(sprite.body.center.x, sprite.body.center.y, 2, 2); - } - - if (sprite2) - { - bmd.fillStyle('#ff00ff'); - bmd.fillRect(sprite2.body.center.x, sprite2.body.center.y, 2, 2); - } - -} - -function render() { - - if (sprite) - { - game.debug.bodyInfo(sprite, 16, 24); - } - - if (sprite2) - { - game.debug.bodyInfo(sprite2, 16, 190); - } - -} diff --git a/examples/wip/misc/bmd.js b/examples/wip/misc/bmd.js deleted file mode 100644 index 36d4e42a7..000000000 --- a/examples/wip/misc/bmd.js +++ /dev/null @@ -1,82 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -var bmd; - -function create() { - - bmd = game.add.bitmapData(32, 64); - - console.log(bmd); - - // And apply it to 100 randomly positioned sprites - for (var i = 0; i < 100; i++) - { - game.add.sprite(game.world.randomX - 32, game.world.randomY - 64, bmd); - } - - // Populate the wave with some data - waveData = game.math.sinCosGenerator(32, 8, 8, 2); - -} - -function update() { - - bmd.clear(); - - updateWobblyBall(); - -} - -// This creates a simple sine-wave effect running through our DynamicTexture. -// This is then duplicated across all sprites using it, meaning we only have to calculate it once. - -var waveSize = 8; -var wavePixelChunk = 2; -var waveData; -var waveDataCounter; - -function updateWobblyBall() -{ - var s = 0; - var copyRect = { x: 0, y: 0, w: wavePixelChunk, h: 32 }; - var copyPoint = { x: 0, y: 0 }; - - for (var x = 0; x < 32; x += wavePixelChunk) - { - copyPoint.x = x; - copyPoint.y = waveSize + (waveSize / 2) + waveData.sin[s]; - - bmd.context.drawImage(game.cache.getImage('ball'), copyRect.x, copyRect.y, copyRect.w, copyRect.h, copyPoint.x, copyPoint.y, copyRect.w, copyRect.h); - - copyRect.x += wavePixelChunk; - - s++; - } - - // Cycle through the wave data - this is what causes the image to "undulate" - game.math.shift(waveData.sin); - - waveDataCounter++; - - if (waveDataCounter == waveData.length) - { - waveDataCounter = 0; - } -} - - -function render() { - - bmd.render(); - -} diff --git a/examples/wip/misc/bmd2.js b/examples/wip/misc/bmd2.js deleted file mode 100644 index 23f586f47..000000000 --- a/examples/wip/misc/bmd2.js +++ /dev/null @@ -1,51 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -var bmd; - -function create() { - - bmd = game.add.bitmapData(800, 600); - - console.log('isLittleEndian', bmd.isLittleEndian); - bmd.isLittleEndian = false; - - bmd.beginPath(); - bmd.beginLinearGradientFill(["#ff0000", "#ffff00"], [0, 1], 0, 0, 0, 600); - bmd.rect(0, 0, 800, 600); - bmd.closePath(); - bmd.fill(); - - bmd.refreshBuffer(); - - for (var i = 0; i < 100; i++) - { - bmd.setPixel(game.world.randomX, game.world.randomY, 0, 0, 0); - } - - var d = game.add.sprite(0, 0, bmd); - -} - -function update() { - - bmd.refreshBuffer(); - bmd.setPixel(game.input.x, game.input.y, 0, 0, 0); - -} - - -function render() { - - bmd.render(); - -} diff --git a/examples/wip/misc/bmd3.js b/examples/wip/misc/bmd3.js deleted file mode 100644 index 007fd8e3b..000000000 --- a/examples/wip/misc/bmd3.js +++ /dev/null @@ -1,74 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - -} - -var bmd; -var img; - -function create() { - - var canvas = Phaser.Canvas.create(800, 600); - var context = canvas.getContext('2d'); - - context.drawImage(game.cache.getImage('atari1'), 0, 0); - - img = context.getImageData(0, 0, 800, 600); - - var data8 = new Uint8ClampedArray(img.data.buffer); - var data32 = new Uint32Array(img.data.buffer); - - context.drawImage(game.cache.getImage('atari1'), 32, 50); - - img = context.getImageData(0, 0, 800, 600); - - // console.log(data32[y * 800 + x]); - - var alpha = 255; - var blue = 50; - var red = 50; - var green = 100; - - for (var y = 0; y < 100; y++) - { - for (var x = 0; x < 250; x++) - { - // var value = x * y & 0xff; - // console.log(data32[y * 800 + x]); - // data32[((y + 100) * 800) + x] = 0; - // data32[y * 800 + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;; - // data32[y * 800 + x] = (red << 24) | (green << 16) | (blue << 8) | alpha; - data32[y * 800 + (x + 300)] = data32[y * 800 + x]; - } - } - - // if (this.isLittleEndian) - // { - // this.data32[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red; - // } - // else - // { - // this.data32[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha; - // } - - img.data.set(data8); - context.putImageData(img, 0, 0); - - document.getElementById('phaser-example').appendChild(canvas); - -} - -function update() { - - -} - - -function render() { - - -} diff --git a/examples/wip/misc/body angle.js b/examples/wip/misc/body angle.js deleted file mode 100644 index 0af8b8e05..000000000 --- a/examples/wip/misc/body angle.js +++ /dev/null @@ -1,50 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('arrow', 'assets/sprites/longarrow.png'); - -} - -var sprite; -var cursors; - - -function create() { - - game.stage.backgroundColor = '#124184'; - - sprite = game.add.sprite(400, 300, 'arrow'); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -100; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 100; - } - - if (cursors.up.isDown) - { - game.physics.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - -} - -function render() { - - game.debug.bodyInfo(sprite, 16, 24); - -} diff --git a/examples/wip/misc/body group.js b/examples/wip/misc/body group.js deleted file mode 100644 index f56f5459b..000000000 --- a/examples/wip/misc/body group.js +++ /dev/null @@ -1,336 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('bullet', 'assets/games/invaders/bullet.png'); - game.load.image('enemyBullet', 'assets/games/invaders/enemy-bullet.png'); - game.load.spritesheet('invader', 'assets/games/invaders/invader32x32x4.png', 32, 32); - game.load.image('ship', 'assets/games/invaders/player.png'); - game.load.spritesheet('kaboom', 'assets/games/invaders/explode.png', 128, 128); - game.load.image('starfield', 'assets/games/invaders/starfield.png'); - game.load.image('background', 'assets/games/starstruck/background2.png'); - -} - -var player; -var aliens; -var bullets; -var bulletTime = 0; -var cursors; -var fireButton; -var explosions; -var starfield; -var score = 0; -var scoreString = ''; -var scoreText; -var lives; -var enemyBullet; -var firingTimer = 0; -var stateText; -var livingEnemies = []; - -var bob; - -function create() { - - $('#step').click(function(){ - console.log('---- STEP', game.stepCount, '-------------------------------'); - game.step(); - }); - - game.enableStep(); - - - // The scrolling starfield background - // starfield = game.add.tileSprite(0, 0, 800, 600, 'starfield'); - - // Our bullet group - // bullets = game.add.group(); - // bullets.createMultiple(30, 'bullet'); - // bullets.setAll('anchor.x', 0.5); - // bullets.setAll('anchor.y', 1); - // bullets.setAll('outOfBoundsKill', true); - - // The enemy's bullets - // enemyBullets = game.add.group(); - // enemyBullets.createMultiple(30, 'enemyBullet'); - // enemyBullets.setAll('anchor.x', 0.5); - // enemyBullets.setAll('anchor.y', 1); - // enemyBullets.setAll('outOfBoundsKill', true); - - // The hero! - // player = game.add.sprite(400, 500, 'ship'); - // player.anchor.setTo(0.5, 0.5); - - // The baddies! - aliens = game.add.group(); - - createAliens(); - - // The score - // scoreString = 'Score : '; - // scoreText = game.add.text(10, 10, scoreString + score, { fontSize: '34px', fill: '#fff' }); - - // Lives - // lives = game.add.group(); - // game.add.text(game.world.width - 100, 10, 'Lives : ', { fontSize: '34px', fill: '#fff' }); - - // Text - // stateText = game.add.text(game.world.centerX,game.world.centerY,'', { fontSize: '84px', fill: '#fff' }); - // stateText.anchor.setTo(0.5, 0.5); - // stateText.visible = false; - - // for (var i = 0; i < 3; i++) - // { - // var ship = lives.create(game.world.width - 100 + (30 * i), 60, 'ship'); - // ship.anchor.setTo(0.5, 0.5); - // ship.angle = 90; - // ship.alpha = 0.4; - // } - - // An explosion pool - // explosions = game.add.group(); - // explosions.createMultiple(30, 'kaboom'); - // explosions.forEach(setupInvader, this); - - // And some controls to play the game with - cursors = game.input.keyboard.createCursorKeys(); - // fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); -} - -function createAliens () { - -/* - for (var y = 0; y < 4; y++) - { - for (var x = 0; x < 10; x++) - { - var alien = aliens.create(x * 48, y * 50, 'invader'); - alien.anchor.setTo(0.5, 0.5); - alien.animations.add('fly', [ 0, 1, 2, 3 ], 20, true); - alien.play('fly'); - } - } -*/ - -bob = game.add.sprite(32, 32, 'invader'); - - // bob = aliens.create(48, 50, 'invader'); - - bob.debug = true; - - aliens.x = 100; - aliens.y = 50; - - // All this does is basically start the invaders moving. Notice we're moving the Group they belong to, rather than the invaders directly. - // var tween = game.add.tween(aliens).to( { x: 200 }, 2000, Phaser.Easing.Linear.None, true, 0, 1000, true); - - // When the tween completes it calls descend, before looping again - // tween.onComplete.add(descend, this); -} - -function setupInvader (invader) { - - invader.anchor.x = 0.5; - invader.anchor.y = 0.5; - invader.animations.add('kaboom'); - -} - -function descend() { - -console.log('descend'); - aliens.y += 10; - -} - -function update() { - - // aliens.x += 1; - bob.body.velocity.x = 100; - // bob.body.velocity.y = 100; - - // Scroll the background - // starfield.tilePosition.y += 2; - - // Reset the player, then check for movement keys - -/* - player.body.velocity.setTo(0, 0); - - if (cursors.left.isDown) - { - player.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - player.body.velocity.x = 200; - } - - // Firing? - if (fireButton.isDown) - { - fireBullet(); - } - - if (game.time.now > firingTimer) - { - enemyFires(); - } - - // Run collision - game.physics.collide(bullets, aliens, collisionHandler, null, this); - game.physics.collide(enemyBullets, player, enemyHitsPlayer, null, this); -*/ - -} - -/* - -function collisionHandler (bullet, alien) { - - // When a bullet hits an alien we kill them both - bullet.kill(); - alien.kill(); - - // Increase the score - score += 20; - scoreText.content = scoreString + score; - - // And create an explosion :) - var explosion = explosions.getFirstDead(); - explosion.reset(alien.body.x, alien.body.y); - explosion.play('kaboom', 30, false, true); - - if (aliens.countLiving() == 0) - { - score += 1000; - scoreText.content = scoreString + score; - - enemyBullets.callAll('kill',this); - stateText.content = " You Won, \n Click to restart"; - stateText.visible = true; - - //the "click to restart" handler - game.input.onTap.addOnce(restart,this); - } - -} - -function enemyHitsPlayer (player,bullet) { - - bullet.kill(); - - live = lives.getFirstAlive(); - - if (live) - { - live.kill(); - } - - // And create an explosion :) - var explosion = explosions.getFirstDead(); - explosion.reset(player.body.x, player.body.y); - explosion.play('kaboom', 30, false, true); - - // When the player dies - if (lives.countLiving() < 1) - { - player.kill(); - enemyBullets.callAll('kill'); - - stateText.content=" GAME OVER \n Click to restart"; - stateText.visible = true; - - //the "click to restart" handler - game.input.onTap.addOnce(restart,this); - } - -} - -function enemyFires () { - - // Grab the first bullet we can from the pool - enemyBullet = enemyBullets.getFirstExists(false); - - livingEnemies.length=0; - - aliens.forEachAlive(function(alien){ - - // put every living enemy in an array - livingEnemies.push(alien); - }); - - - if (enemyBullet && livingEnemies.length > 0) - { - - var random=game.rnd.integerInRange(0,livingEnemies.length); - - // randomly select one of them - var shooter=livingEnemies[random]; - // And fire the bullet from this enemy - enemyBullet.reset(shooter.body.x, shooter.body.y); - - game.physics.moveToObject(enemyBullet,player,120); - firingTimer = game.time.now + 2000; - } - -} - -function fireBullet () { - - // To avoid them being allowed to fire too fast we set a time limit - if (game.time.now > bulletTime) - { - // Grab the first bullet we can from the pool - bullet = bullets.getFirstExists(false); - - if (bullet) - { - // And fire it - bullet.reset(player.x, player.y + 8); - bullet.body.velocity.y = -400; - bulletTime = game.time.now + 200; - } - } - -} - -function resetBullet (bullet) { - - // Called if the bullet goes out of the screen - bullet.kill(); - -} - -function restart () { - - // A new level starts - - //resets the life count - lives.callAll('revive'); - // And brings the aliens back from the dead :) - aliens.removeAll(); - createAliens(); - - //revives the player - player.revive(); - //hides the text - stateText.visible = false; - -} - -*/ - -function render() { - - for (var i = 0; i < aliens._container.children.length; i++) - { - // game.debug.physicsBody(aliens._container.children[i].body); - } - - game.debug.physicsBody(bob.body); - -} \ No newline at end of file diff --git a/examples/wip/misc/body scale.js b/examples/wip/misc/body scale.js deleted file mode 100644 index 73c716507..000000000 --- a/examples/wip/misc/body scale.js +++ /dev/null @@ -1,48 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - -} - -var sprite; -var sprite2; - -function create() { - - game.stage.backgroundColor = '#124184'; - - // Here we're tweening the scale of the sprite, which translates to the scale of the Body as well - // The collision will carry on working even against the scaled body. - - sprite = game.add.sprite(200, 300, 'gameboy', 2); - sprite.name = 'green'; - // sprite.anchor.setTo(0.5, 0.5); - sprite.body.immovable = true; - - sprite2 = game.add.sprite(600, 300, 'gameboy', 3); - sprite2.name = 'yellow'; - sprite2.body.rebound = false; - - // sprite2.body.velocity.x = -200; - - game.add.tween(sprite2).to( { x: 0 }, 3000, Phaser.Easing.Linear.None, true); - - // game.add.tween(sprite.scale).to( { x: 3, y: 3 }, 2000, Phaser.Easing.Linear.None, true, 0, 1000, true); - -} - -function update() { - - game.physics.collide(sprite, sprite2); - -} - -function render() { - - game.debug.polygon(sprite.body.polygons, 'rgb(255,0,0)'); - game.debug.polygon(sprite2.body.polygons, 'rgb(255,0,0)'); - -} diff --git a/examples/wip/misc/body test.js b/examples/wip/misc/body test.js deleted file mode 100644 index e9a1522d4..000000000 --- a/examples/wip/misc/body test.js +++ /dev/null @@ -1,76 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -var group; -var group2; - -var atari; -var coke; -var dropper; - -function create() { - - // make our world wider - game.world.setBounds(0, 0, 2000, 600); - - // shift the camera (still works) - // game.camera.x = 400; - game.world.angle = 10; - - // base group - group = game.add.group(); - // group.angle = 10; - group.y = 200; - - atari = group.create(0, 0, 'atari1'); - coke = group.create(340, 0, 'coke'); - - // dropper group - group2 = game.add.group(); - - dropper = group2.create(400, 0, 'mushroom'); - dropper.inputEnabled = true; - dropper.input.enableDrag(); - dropper.events.onDragStop.add(checkDrop, this); - - group2.y = 400; - -} - -function checkDrop() { - - if (Phaser.Rectangle.intersects(dropper.body, atari.body)) - { - atari.alpha = 0.3; - } - else if (Phaser.Rectangle.intersects(dropper.body, coke.body)) - { - coke.alpha = 0.3; - } - -} - -function update() { - - group.x += 0.5; - -} - -function render() { - - game.debug.text(dropper.position.x, 200, 32); - game.debug.text(dropper.position.y, 260, 32); - - game.debug.geom(atari.body, 'rgba(255,0,0,0.3)'); - game.debug.geom(coke.body, 'rgba(255,0,0,0.3)'); - game.debug.geom(dropper.body, 'rgba(0,255,0,0.3)'); - -} diff --git a/examples/wip/misc/bunny.js b/examples/wip/misc/bunny.js deleted file mode 100644 index 518e52a74..000000000 --- a/examples/wip/misc/bunny.js +++ /dev/null @@ -1,55 +0,0 @@ - - GameState = function (game) { - this.game = game; - }; - - GameState.prototype = Object.create(Phaser.State.prototype); - GameState.prototype.constructor = GameState; - - GameState.prototype.preload = function preload() { - this.game.load.image('bunny', 'assets/sprites/bunny.png'); - this.game.load.image('carrot', 'assets/sprites/carrot.png'); - this.game.load.image('melon', 'assets/sprites/melon.png'); - } - - GameState.prototype.create = function () { - this.game.world.setBounds(0, 0, 1600, 600); - - this.bunny = this.game.add.sprite(200, 200, 'bunny'); - this.bunny.scale.setTo(0.2, 0.2); - - var melon = this.game.add.sprite(0, 0, 'melon'); - this.melonGroup = this.game.add.group(null, 'melonGroup'); - this.melonGroup.add(melon); - melon.x = this.bunny.x; - melon.y = this.bunny.y - 40; - - this.carrot = this.game.add.sprite(0, 0, 'carrot'); - - this.game.camera.follow(this.bunny); - } - - GameState.prototype.update = function () { - this.bunny.body.velocity.x = 0; - - if (this.game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { - this.bunny.body.velocity.x = 500; - } - - if (this.game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { - this.bunny.body.velocity.x = -500; - } - - var melon = this.melonGroup.getFirstExists(true); - melon.x = this.bunny.x; - melon.y = this.bunny.y - 40; - - this.carrot.x = this.bunny.x; - this.carrot.y = this.bunny.y - 20; - - }; - - (function () { - var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example'); - game.state.add('state', GameState, true); - })(); diff --git a/examples/wip/misc/button scale.js b/examples/wip/misc/button scale.js deleted file mode 100644 index 7e35e4c67..000000000 --- a/examples/wip/misc/button scale.js +++ /dev/null @@ -1,114 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - // Enable scaling - // game.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - // game.stage.scale.maxWidth = 1500; - // game.stage.scale.maxHeight = 1000; - // game.stage.scale.startFullScreen(); - // game.stage.scale.refresh(); - - game.load.spritesheet('button', 'assets/buttons/button_sprite_sheet.png', 193, 71); - - game.load.image('sky0','assets/skies/space2.png'); - game.load.image('sky1','assets/skies/cavern1.png'); - game.load.image('sky2','assets/skies/chrome.png'); - game.load.image('sky3','assets/skies/fire.png'); - game.load.image('sky4','assets/skies/fog.png'); - game.load.image('sky5','assets/skies/sky1.png'); - game.load.image('sky6','assets/skies/toxic.png'); - -} - -var background; -var button1; -var button2; -var button3; -var button4; -var button5; -var button6; - -function create() { - - console.log('create!'); - - background = game.add.sprite(0, 0, 'sky0'); - background.name = 'background'; - - // Standard button (also used as our pointer tracker) - button1 = game.add.button(100, 100, 'button', changeSky, this, 2, 1, 0); - button1.name = 'sky1'; - button1.anchor.setTo(0.5, 0.5); - - // Rotated button - button2 = game.add.button(330, 200, 'button', changeSky, this, 2, 1, 0); - button2.name = 'sky2'; - button2.angle = 24; - button2.anchor.setTo(0.5, 0.5); - - // Width scaled button - button3 = game.add.button(100, 300, 'button', changeSky, this, 2, 1, 0); - button3.name = 'sky3'; - button3.width = 300; - button3.anchor.setTo(0, 0.5); - // button3.angle = 0.1; - - // Scaled button - button4 = game.add.button(300, 450, 'button', changeSky, this, 2, 1, 0); - button4.name = 'sky4'; - button4.scale.setTo(2, 2); - - // Shrunk button - button5 = game.add.button(100, 450, 'button', changeSky, this, 2, 1, 0); - button5.name = 'sky5'; - button5.scale.setTo(0.5, 0.5); - - // Scaled and Rotated button - button6 = game.add.button(570, 200, 'button', changeSky, this, 2, 1, 0); // anchor 0.5 - button6.name = 'sky6'; - button6.angle = 32; - button6.scale.setTo(2, 2); - button6.anchor.setTo(0.5, 0.5); - - // works regardless of world angle, parent angle or camera position - // game.world.setBounds(0, 0, 2000, 2000); - // game.world.angle = 10; - // game.camera.x = 300; - - // Phaser.Canvas.setSmoothingEnabled(false); - - //game.input.onDown.add(gofull, this); - -} - -function gofull() { - - game.stage.scale.startFullScreen(false); - -} - -function changeSky (button) { - - background.loadTexture(button.name); - -} - -function render () { - - // game.debug.spriteCorners(button1, false, true); - // game.debug.spriteCorners(button2, false, true); - // game.debug.spriteCorners(button3, false, true); - // game.debug.spriteCorners(button4, false, true); - // game.debug.spriteCorners(button5, false, true); - // game.debug.spriteCorners(button6, false, true); - - // game.debug.text('sx: ' + button3.scale.x + ' sy: ' + button3.scale.y + ' w: ' + button3.width + ' cw: ' + button3._cache.width, 32, 20); - // game.debug.text('ox: ' + game.stage.offset.x + ' oy: ' + game.stage.offset.y, 32, 20); - // game.debug.point(button3.input._tempPoint); - // game.debug.point(button6.input._tempPoint); - - game.debug.inputInfo(32, 32); - -} diff --git a/examples/wip/misc/button size.js b/examples/wip/misc/button size.js deleted file mode 100644 index 7199289b6..000000000 --- a/examples/wip/misc/button size.js +++ /dev/null @@ -1,42 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.spritesheet('button', 'assets/buttons/button_sprite_sheet.png', 193, 71); - game.load.image('background','assets/misc/starfield.jpg'); - -} - -var button; -var background; - -function create() { - - game.stage.backgroundColor = '#182d3b'; - - background = game.add.tileSprite(0, 0, 800, 600, 'background'); - - button = game.add.button(game.world.centerX - 95, 200, 'button', actionOnClick, this, 2, 1, 0); - button.anchor.setTo(0.5, 0.5); - - button.scale.setTo(2, 2); - // button.width = 100; - // button.height = 300; - button.angle = 10; - -} - -function actionOnClick () { - - background.visible =! background.visible; - -} - -function render () { - - game.debug.spriteCorners(button); - - game.debug.point(button.input._tempPoint); - -} diff --git a/examples/wip/misc/circlebox.js b/examples/wip/misc/circlebox.js deleted file mode 100644 index 6a22acdec..000000000 --- a/examples/wip/misc/circlebox.js +++ /dev/null @@ -1,70 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('wizball', 'assets/sprites/wizball.png'); - game.load.image('platform', 'assets/sprites/interference_tunnel.png'); - -} - -var ball; -var circle; -var platform; - -function create() { - - // Our ball sprite - ball = game.add.sprite(440, 100, 'wizball'); - ball.anchor.setTo(0.5, 0.5); - - ball.body.customSeparateX = true; - ball.body.customSeparateY = true; - - ball.body.velocity.y = 150; - ball.body.bounce.y = 0.9; - - // Our collision circle - circle = new Phaser.Circle(200, 100, 188); - - // Our platform - platform = game.add.sprite(200, 450, 'platform'); - platform.body.immovable = true; - -} - -function update() { - - // ball.x = game.input.x; - // ball.y = game.input.y; - - circle.x = ball.x; - circle.y = ball.y; - - // This is a rect vs. rect collision. The callback will check the circle. - game.physics.overlap(ball, platform, collisionCallback, processCallback, this); - -} - -function collisionCallback(a, b) { - - ball.body.y -= 10; - ball.body.velocity.y *= -1 * ball.body.bounce.y; - -} - -function processCallback(a, b) { - - return (Phaser.Circle.intersectsRectangle(circle, platform.body)); - -} - -function render() { - - game.debug.text(Phaser.Circle.intersectsRectangle(circle, platform.body), 32, 32); - game.debug.text(ball.body.velocity.y, 32, 64); - // game.debug.text(ball.body.overlapY, 64, 64); - game.debug.circle(circle); - game.debug.geom(platform.body); - -} diff --git a/examples/wip/misc/commando.js b/examples/wip/misc/commando.js deleted file mode 100644 index 3c18aecf1..000000000 --- a/examples/wip/misc/commando.js +++ /dev/null @@ -1,137 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/maps/commando.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/maps/commando.png'); - game.load.image('phaser', 'assets/sprites/arrow.png'); - -} - -var cursors; -var map; -var layer; -var sprite; - -function create() { - - map = game.add.tilemap('map'); - - map.addTilesetImage('CommandoMap1-1BG_bank.png', 'tiles'); - - layer = map.createLayer('ShoeBox Tile Grab'); - // layer.debug = true; - layer.resizeWorld(); - - sprite = game.add.sprite(260, 100, 'phaser'); - sprite.anchor.setTo(0.5, 0.5); - - sprite.body.setSize(16, 16, 8, 8); - - // We'll set a lower max angular velocity here to keep it from going totally nuts - sprite.body.maxAngular = 500; - - // Apply a drag otherwise the sprite will just spin and never slow down - sprite.body.angularDrag = 50; - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - -/* - if (cursors.left.isDown) - { - game.camera.x -= 1; - } - else if (cursors.right.isDown) - { - game.camera.x += 1; - } - - if (cursors.up.isDown) - { - layer.scrollY -= 4; - } - else if (cursors.down.isDown) - { - layer.scrollY += 4; - } -*/ - game.physics.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - // sprite.body.acceleration.x = 0; - // sprite.body.angularAcceleration = 0; - - if (cursors.left.isDown) - { - // sprite.body.acceleration.x = -200; - sprite.body.angularVelocity = -300; - // sprite.body.angularAcceleration -= 200; - } - else if (cursors.right.isDown) - { - // sprite.body.acceleration.x = 200; - sprite.body.angularVelocity = 300; - // sprite.body.angularAcceleration += 200; - } - - if (cursors.up.isDown) - { - game.physics.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - else - { - // game.physics.velocityFromAngle(sprite.angle, sprite.body.velocity, sprite.body.velocity); - } - - /* - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - sprite.angle = sprite.angle + 1; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -900; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 900; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -900; - // sprite.scale.x = -1; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 900; - // sprite.scale.x = 1; - } - */ - - -} - -function render() { - - // game.debug.spriteBody(sprite); - // game.debug.spriteBounds(sprite); - - // game.debug.text(sprite.x, 32, 32); - // game.debug.text(sprite.y, 32, 48); - - // game.debug.text(layer.scrollX, 32, 32); - // game.debug.text(layer.scrollY, 32, 48); - -} \ No newline at end of file diff --git a/examples/wip/misc/create map polygon.js b/examples/wip/misc/create map polygon.js deleted file mode 100644 index c461bf3a0..000000000 --- a/examples/wip/misc/create map polygon.js +++ /dev/null @@ -1,234 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.tilemap('map', 'assets/tilemaps/maps/platform.json', null, Phaser.Tilemap.TILED_JSON); - // game.load.image('platformer_tiles', 'assets/tilemaps/tiles/platformer_tiles.png'); - - game.load.tilemap('map', 'assets/tilemaps/maps/features_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('walls_1x2', 'assets/tilemaps/tiles/walls_1x2.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - - -} - -var map; -var layer; -var mapLayer; - -var polys = []; -var tiles = []; -var idx = 0; -var group = []; - -function create() { - - game.stage.backgroundColor = '#124184'; - - // map = game.add.tilemap('map'); - // map.addTilesetImage('platformer_tiles'); - // map.setCollisionBetween(21, 53); - // layer = map.createLayer('Tile Layer 1'); - // layer.debug = true; - - map = game.add.tilemap('map'); - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('walls_1x2'); - map.addTilesetImage('tiles2'); - map.setCollisionBetween(1, 12); - layer = map.createLayer('Tile Layer 1'); - - mapLayer = map.layers[0]; - - tiles = getInterestingTiles(); - - console.log('found',tiles.length,'interesting tiles'); - - - // group = []; - - // var tile = getFirstUnscanned(); - - // console.log('starting from', tile); - - // floodFill(tile); - - // console.log('group collected, size', group.length); - - // now scan the group - // scanEdges(); - - - - // works great :) - while (getScannedLeft() > 0) { - - // group = []; - - var tile = getFirstUnscanned(); - - console.log('starting from', tile); - - floodFill(tile); - - console.log('group collected, size', group.length); - - console.log('remaining: ', getScannedLeft()); - - } - -} - -function getFirstUnscanned() { - - for (var i = 0; i < tiles.length; i++) - { - if (!tiles[i].scanned) - { - return tiles[i]; - } - } - -} - -function getScannedLeft() { - - var total = tiles.length; - - for (var i = 0; i < tiles.length; i++) - { - if (tiles[i].scanned) - { - total--; - } - } - - return total; - -} - -var current; - -function scanEdges() { - - var points = []; - - var start = group[0]; - - // special case for when group.length = 1 should go here - - - -} - -function scanTop(origin) { - -} - -function floodFill(origin) { - - if (origin.scanned === true) - { - return; - } - - origin.scanned = true; - - group.push(origin); - - // console.log('ff origin', origin.x, origin.y); - - var west = map.getTileLeft(0, origin.x, origin.y); - - if (west && (west.faceTop || west.faceBottom || west.faceLeft || west.faceRight)) - { - // console.log('west found', west); - floodFill(west); - } - - var east = map.getTileRight(0, origin.x, origin.y); - - if (east && (east.faceTop || east.faceBottom || east.faceLeft || east.faceRight)) - { - // console.log('east found', east); - floodFill(east); - } - - var north = map.getTileAbove(0, origin.x, origin.y); - - if (north && (north.faceTop || north.faceBottom || north.faceLeft || north.faceRight)) - { - // console.log('north found', north); - floodFill(north); - } - - var south = map.getTileBelow(0, origin.x, origin.y); - - if (south && (south.faceTop || south.faceBottom || south.faceLeft || south.faceRight)) - { - // console.log('south found', south); - floodFill(south); - } - -} - -function getInterestingTiles() { - - var tiles = []; - - for (var y = 0, h = mapLayer.height; y < h; y++) - { - for (var x = 0, w = mapLayer.width; x < w; x++) - { - var tile = mapLayer.data[y][x]; - - if (tile && (tile.faceTop || tile.faceBottom || tile.faceLeft || tile.faceRight)) - { - // reset the scanned status - tile.scanned = false; - tiles.push(tile); - } - } - } - - return tiles; - -} - -function getTile() { - - for (var y = 0, h = mapLayer.height; y < h; y++) - { - for (var x = 0, w = mapLayer.width; x < w; x++) - { - var tile = mapLayer.data[y][x]; - - if (tile && (tile.faceTop || tile.faceBottom || tile.faceLeft || tile.faceRight)) - { - return tile; - } - } - } - -} - -function update() { - - -} - -function render() { - - if (group) - { - game.context.fillStyle = 'rgba(255,0,0,0.7)'; - - for (var i = 0; i < group.length; i++) - { - game.context.fillRect(group[i].x * group[i].width, group[i].y * group[i].height, group[i].width, group[i].height); - } - } - -} \ No newline at end of file diff --git a/examples/wip/misc/crop.js b/examples/wip/misc/crop.js deleted file mode 100644 index f6f846a02..000000000 --- a/examples/wip/misc/crop.js +++ /dev/null @@ -1,24 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - -} - -var atari; - -function create() { - - atari = game.add.sprite(300, 300, 'atari1'); - - // atari.crop = new Phaser.Rectangle(0, 0, 10, atari.height); - -} - -function update() { - - atari.crop.width -= 1; - -} diff --git a/examples/wip/misc/cursor.js b/examples/wip/misc/cursor.js deleted file mode 100644 index 7c30443f6..000000000 --- a/examples/wip/misc/cursor.js +++ /dev/null @@ -1,55 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('atari2', 'assets/sprites/atari800xl.png'); - game.load.image('atari4', 'assets/sprites/atari800.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - game.load.image('duck', 'assets/sprites/darkwing_crazy.png'); - game.load.image('firstaid', 'assets/sprites/firstaid.png'); - game.load.image('diamond', 'assets/sprites/diamond.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -var group; - -function create() { - - group = game.add.group(); - - var sprite1 = group.create(0, 200, 'atari1'); - sprite1.name = 'Atari 1'; - - var sprite2 = group.create(300, 200, 'atari2'); - sprite2.name = 'Atari 2'; - - var sprite3 = group.create(600, 200, 'atari4'); - sprite3.name = 'Atari 3'; - - game.input.onDown.add(moveCursor, this); - - group.dump(false); - -} - -function moveCursor () { - - group.next(); - group.dump(false); - -} - -function update() { - - -} - -function render() { - - game.debug.text(group.cursor.name, 32, 32); - - // game.debug.inputInfo(32, 32); - -} \ No newline at end of file diff --git a/examples/wip/misc/demo worm.js b/examples/wip/misc/demo worm.js deleted file mode 100644 index 8c764ee1c..000000000 --- a/examples/wip/misc/demo worm.js +++ /dev/null @@ -1,79 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -var sprite; -var particles = []; -var bmd; - -var u = 0; -var n = 0; -var oldn = 0; -var ad = 0; - -function create() { - - bmd = game.add.bitmapData(800, 600); - - for (var i = 0; i < 60; i++) - { - particles.push(new Phaser.Point(0, 0)); - } - - sprite = game.add.sprite(0, 0, bmd); - -} - -function mycircle(context, x, y, R, color) { - - //R = 64; - - context.fillStyle = color; - context.beginPath(); - context.arc(x, y, R, 0, Math.PI * 2, true); - context.closePath(); - context.fill(); - -} - -function update() { - - bmd.clear(); - - oldn = n; - - for (var t = 0; t < particles.length; t++) - { - var p = particles[t]; - - // p.x = Math.sin(n) * 50 + Math.cos(n * 1.5) * 300; - // p.y = Math.sin(n / 2) * 20 + Math.sin(n * 2) * 250; - - p.x = Math.cos(n) * 50 + Math.sin(n * 1.5) * 300; - p.y = Math.cos(n / 2) * 20 + Math.cos(n * 2) * 250; - - var tx = p.x; - var ty = p.y; - - bmd.context.globalCompositeOperation = 'xor'; - - //mycircle(bmd.context, p.x + 400, p.y + 300, Math.sin(t * 360 / particles.length / 2 * Math.PI / 180) * 50, 'rgba(255, 255, 0, 1)'); - mycircle(bmd.context, p.x + 400, p.y + 300, Math.sin(t * 360 / particles.length / 2 * Math.PI / 180) * 50, 'rgba(255, 255, 0, 1)'); - - n += 0.05; - - //bmd.context.globalCompositeOperation = 'source-over'; - } - - n = oldn + 0.02; - -} - -function render() { - -} diff --git a/examples/wip/misc/dragonfire.js b/examples/wip/misc/dragonfire.js deleted file mode 100644 index 3525bac3b..000000000 --- a/examples/wip/misc/dragonfire.js +++ /dev/null @@ -1,53 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -var background; -var filter; - -function preload() { - - game.load.spritesheet('dragon', 'assets/sprites/stormlord-dragon96x64.png', 96, 64); - game.load.image('sky', 'assets/skies/sky2.png'); - game.load.image('land', 'assets/wip/karamoon.png'); - game.load.script('fire', '../filters/Fire.js'); - -} - -var sky; -var background; -var fire; -var dragon; - -function create() { - - sky = game.add.sprite(0, 600, 'sky'); - sky.scale.y = -1; - sky.alpha = 0.5; - - fire = game.add.sprite(0, 200); - fire.width = 800; - fire.height = 400; - - background = game.add.sprite(0, 0, 'land'); - - dragon = game.add.sprite(100, 300, 'dragon'); - dragon.animations.add('flyright', [0,1,2,3,4,5], 10, true); - dragon.play('flyright'); - - filter = game.add.filter('Fire', 800, 400); - filter.alpha = 0.0; - fire.filters = [filter]; - -} - -function update() { - - filter.update(); - -} - -function render() { - - // filter.update(); - -} diff --git a/examples/wip/misc/fiddle.js b/examples/wip/misc/fiddle.js deleted file mode 100644 index 62c9427e7..000000000 --- a/examples/wip/misc/fiddle.js +++ /dev/null @@ -1,29 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('ball', 'assets/sprites/yellow_ball.png'); - -} - -var ball; - -function create() { - - ball = game.add.sprite(300, 0, 'ball'); - - TweenLite.to(ball, 10, { y: 400 }); -} - -function startBounceTween() { - - // ball.y = 0; - - // var bounce=game.add.tween(ball); - - // bounce.to({ y: game.world.height-ball.height }, 1000 + Math.random() * 3000, Phaser.Easing.Bounce.In); - // bounce.onComplete.add(startBounceTween, this); - // bounce.start(); - -} diff --git a/examples/wip/misc/filterconv.php b/examples/wip/misc/filterconv.php deleted file mode 100644 index 0475bc501..000000000 --- a/examples/wip/misc/filterconv.php +++ /dev/null @@ -1,110 +0,0 @@ - - - - - - phaser - ShaderToy Convertor - - - - -

ShaderToy to PIXI Convertor

- -
- -

Input

- - -

Output

- - -
- - - -
- - - \ No newline at end of file diff --git a/examples/wip/misc/fixdrag.js b/examples/wip/misc/fixdrag.js deleted file mode 100644 index e8baa82ca..000000000 --- a/examples/wip/misc/fixdrag.js +++ /dev/null @@ -1,72 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.stage.backgroundColor = '#007236'; - - game.load.image('ball', 'assets/sprites/shinyball.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('phaser', 'assets/sprites/sonic_havok_sanity.png'); - -} - -var sprite; -var cursors; - -function create() { - - game.world.setBounds(0, 0, 1000, 1000); - - for (var i = 0; i < 100; i++) - { - game.add.sprite(game.world.randomX, game.world.randomY, 'mushroom'); - } - - sprite = game.add.sprite(200, 200, 'ball'); - - sprite.fixedToCamera = true; - // sprite.cameraOffset.setTo(200, 200); - - - sprite.inputEnabled = true; - sprite.input.enableDrag(); - sprite.events.onInputOver.add(wibble, this); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function wibble() { - console.log('over'); -} - -function update() { - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - -} - -function render() { - - game.debug.text(sprite.cameraOffset.x, 32, 32); - game.debug.text(sprite.cameraOffset.y, 32, 64); - game.debug.pointer(game.input.activePointer); - -} diff --git a/examples/wip/misc/forum.js b/examples/wip/misc/forum.js deleted file mode 100644 index b7a4d2189..000000000 --- a/examples/wip/misc/forum.js +++ /dev/null @@ -1,47 +0,0 @@ -var mainMenu = { - - preload: function () { - - // game.load.image('bg', 'assets/bg.png'); - // game.load.image('mainstart', 'assets/mainstart.png'); - game.load.image('bg', 'assets/pics/louie-inga.png'); - game.load.image('mainstart', 'assets/pics/contra2.png'); - - }, - - create: function () { - - game.add.sprite(0, 0, 'bg'); - - var mainstart = game.add.sprite(0, 0, 'mainstart'); - mainstart.name = "mainstart"; - mainstart.inputEnabled = true; - mainstart.events.onInputDown.add(this.listener, this); - - }, - - listener: function () - { - game.state.start('levelMenu', true, true); - } - -} - -var levelSelect = { - - preload: function () { - }, - - create: function () { - - game.add.sprite(0, 0, 'bg'); - - } - -} - -var game = new Phaser.Game(640, 480); - -game.state.add('menu', mainMenu, true); -game.state.add('levelMenu', levelSelect); - diff --git a/examples/wip/misc/gc1.js b/examples/wip/misc/gc1.js deleted file mode 100644 index 2c0900a6c..000000000 --- a/examples/wip/misc/gc1.js +++ /dev/null @@ -1,14 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { -} - -function create() { -} - -function update() { -} - -function render() { -} diff --git a/examples/wip/misc/gravity.js b/examples/wip/misc/gravity.js deleted file mode 100644 index 1268c2344..000000000 --- a/examples/wip/misc/gravity.js +++ /dev/null @@ -1,39 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - game.load.image('arrow', 'assets/sprites/arrow.png'); - -} - -var sprite; - -var setGravityToPointXY = function(game,sprite,power, radiusLow,radiusHigh,pointX,pointY){ - var pointXY = new Phaser.Point(pointX,pointY); - var tempDistance = Phaser.Point.distance(sprite,pointXY); - if(tempDistance>radiusLow&&tempDistance -1){ - - C.x = pa[n].x; - C.y = pa[n].y; - - if(n > 0){ - - cx+=C.x; - cy+=C.y; - - D=Point(pa[n-1])||Point(pa[0]); - - i=lineIntersectLine(A,B,C,D); - - if(i != null){ - result.intersections.push(i); - } - if(lineIntersectLine(A,new Point(C.x+D.x,A.y),C,D) != null){ - An++; - } - if(lineIntersectLine(B,new Point(C.x+D.x,B.y),C,D) != null){ - Bn++; - } - } - n--; - } - if(An % 2 == 0){ - result.start_inside=true; - } - if(Bn % 2 == 0){ - result.end_inside=true; - } - result.centroid=new Point(cx/(pa.length-1),cy/(pa.length-1)); - result.intersects = result.intersections.length > 0; - return result; -} -*/ - -var c = 'rgb(255,255,255)'; -var p = new Phaser.Point(); - -function update() { - - line1.fromSprite(handle1, handle2, true); - line2.fromSprite(handle3, handle4, true); - - p = line1.intersects(line2, true); - - if (p) - { - c = 'rgb(0,255,0)'; - } - else - { - c = 'rgb(255,255,255)'; - } - -} - -function render() { - - game.debug.line(line1, c); - game.debug.line(line2, c); - - game.debug.lineInfo(line1, 32, 32); - game.debug.lineInfo(line2, 32, 100); - - if (p) - { - game.context.fillStyle = 'rgb(255,0,255)'; - game.context.fillRect(p.x - 2, p.y - 2, 5, 5); - } - -} \ No newline at end of file diff --git a/examples/wip/misc/line polygon.js b/examples/wip/misc/line polygon.js deleted file mode 100644 index 9467cab39..000000000 --- a/examples/wip/misc/line polygon.js +++ /dev/null @@ -1,163 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('balls', 'assets/sprites/balls.png', 17, 17); - -} - -var handle1; -var handle2; - -var line; -var polygon; - -function create() { - - game.stage.backgroundColor = '#124184'; - - handle1 = game.add.sprite(100, 150, 'balls', 0); - handle1.inputEnabled = true; - handle1.input.enableDrag(true); - - handle2 = game.add.sprite(400, 200, 'balls', 0); - handle2.inputEnabled = true; - handle2.input.enableDrag(true); - - line = new Phaser.Line(handle1.x, handle1.y, handle2.x, handle2.y); - - polygon = new SAT.Polygon(new SAT.Vector(300, 300), [new SAT.Vector(0, 50), new SAT.Vector(100, 50), new SAT.Vector(100, 0), new SAT.Vector(150, 0), new SAT.Vector(150, 150), new SAT.Vector(100, 150), new SAT.Vector(100, 100), new SAT.Vector(0, 100), new SAT.Vector(0, 50)]); - -} - -/*--------------------------------------------------------------------------- -Returns an Object with the following properties: -intersects -Boolean indicating if an intersection exists. -start_inside -Boolean indicating if Point A is inside of the polygon. -end_inside -Boolean indicating if Point B is inside of the polygon. -intersections -Array of intersection Points along the polygon. -centroid -A Point indicating "center of mass" of the polygon. - -"pArry" is an Array of Points. -----------------------------------------------------------------------------*/ - -function lineIntersectPoly(A, B, polygon) { - - var An =1; - var Bn =1; - var C = {x: 0, y: 0}; - var D = {x: 0, y: 0}; - var i = {x: 0, y: 0}; - var cx=0; - var cy=0; - var result = {}; - - var pa = []; - - for (var pi = 0; pi < polygon.points.length; pi++) - { - pa.push({ x: polygon.points[pi].x + polygon.pos.x, y: polygon.points[pi].y + polygon.pos.y }) - } - - pa.push(pa[0]); //Create line from last Point to beginning Point - - result.intersects = false; - result.intersections=[]; - result.start_inside=false; - result.end_inside=false; - - var n = pa.length-1; - - while(n > -1){ - - C.x = pa[n].x; - C.y = pa[n].y; - - if(n > 0){ - - cx+=C.x; - cy+=C.y; - - D.x = pa[n-1].x || pa[0].x; - D.y = pa[n-1].y || pa[0].y; - - i=Phaser.Line.intersectsPoints(A,B,C,D); - - if(i != null){ - result.intersections.push(i); - } - if(Phaser.Line.intersectsPoints(A,new Phaser.Point(C.x+D.x,A.y),C,D) != null){ - An++; - } - if(Phaser.Line.intersectsPoints(B,new Phaser.Point(C.x+D.x,B.y),C,D) != null){ - Bn++; - } - } - n--; - } - if(An % 2 == 0){ - result.start_inside=true; - } - if(Bn % 2 == 0){ - result.end_inside=true; - } - result.centroid=new Phaser.Point(cx/(pa.length-1),cy/(pa.length-1)); - result.intersects = result.intersections.length > 0; - return result; -} - -var c = 'rgb(255,255,255)'; -var p = new Phaser.Point(); -var result = {}; - -function update() { - - line.fromSprite(handle1, handle2, true); - - result = lineIntersectPoly(line.start, line.end, polygon); - - handle1.frame = 0; - handle2.frame = 0; - - if (result.intersects) - { - c = 'rgb(0,255,0)'; - - if (result.start_inside) - { - handle1.frame = 1; - } - - if (result.end_inside) - { - handle2.frame = 1; - } - } - else - { - c = 'rgb(255,255,255)'; - } - -} - -function render() { - - game.debug.line(line, c); - game.debug.lineInfo(line, 32, 32); - - game.debug.polygon(polygon); - - if (result.intersects) - { - game.debug.text(result.intersects, 32, 100); - - game.context.fillStyle = 'rgb(255,0,255)'; - - for (var i = 0; i < result.intersections.length; i++) - { - game.context.fillRect(result.intersections[i].x - 2, result.intersections[i].y - 2, 5, 5); - } - } - -} \ No newline at end of file diff --git a/examples/wip/misc/mariotogether.js b/examples/wip/misc/mariotogether.js deleted file mode 100644 index 8b3bf173b..000000000 --- a/examples/wip/misc/mariotogether.js +++ /dev/null @@ -1,46 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.tilemap('nes', 'assets/maps/mario1.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tilesNes', 'assets/maps/mario1.png',16,16); - - game.load.tilemap('snes', 'assets/maps/smb_level1.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tilesSnes', 'assets/maps/smb_tiles.png',16,16); -} - -function create() { - - game.stage.backgroundColor = '#5c94fc'; - - mapNes = game.add.tilemap('nes'); - - tilesetNes = game.add.tileset('tilesNes'); - - - layerNes = game.add.tilemapLayer(0, 0, mapNes.layers[0].width*tilesetNes.tileWidth, 600, tilesetNes, mapNes, 0); - - layerNes.fixedToCamera=false; - - layerNes.resizeWorld(); - - - mapSnes = game.add.tilemap('snes'); - - tilesetSnes = game.add.tileset('tilesSnes'); - - - layerSnes = game.add.tilemapLayer(0, 168, mapSnes.layers[0].width*tilesetSnes.tileWidth, 600, tilesetSnes, mapSnes, 0); - - layerSnes.fixedToCamera=false; - - game.add.tween(game.camera).to( { x: 5120-800 }, 30000, Phaser.Easing.Linear.None, true, 0, 1000, true); - - game.input.onDown.add(goFull, this); - -} - -function goFull() { - game.stage.scale.startFullScreen(); -} diff --git a/examples/wip/misc/mod.js b/examples/wip/misc/mod.js deleted file mode 100644 index fd534bb58..000000000 --- a/examples/wip/misc/mod.js +++ /dev/null @@ -1,174 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.script('pt', 'wip/pt.js'); - game.load.binary('impulse', 'assets/audio/protracker/act_of_impulse.mod', modLoaded, this); - game.load.binary('macrocosm', 'assets/audio/protracker/macrocosm.mod', modLoaded, this); - game.load.binary('enigma', 'assets/audio/protracker/enigma.mod', modLoaded, this); - game.load.binary('elysium', 'assets/audio/protracker/elysium.mod', modLoaded, this); - game.load.binary('stardust', 'assets/audio/protracker/sd-ingame1.mod', modLoaded, this); - game.load.binary('globaltrash', 'assets/audio/protracker/global_trash_3_v2.mod', modLoaded, this); - game.load.image('vu1', 'assets/sprites/flectrum.png'); - game.load.image('vu2', 'assets/sprites/flectrum2.png'); - game.load.image('vu3', 'assets/sprites/healthbar.png'); - -} - -function modLoaded(key, data) { - - console.log('module loaded:', key); - - var buffer = new Uint8Array(data); - - return buffer; - -} - -var vu1; -var vu2; -var vu3; -var vu4; - -var modsample = new Array(); -var module; - -var sample1; -var sample2; -var sample3; -var sample4; -var sampleName1; -var sampleName2; -var sampleName3; -var sampleName4; - -var r1; -var r2; -var r3; -var r4; - -function create() { - - // vu1 = game.add.sprite(400, 100, 'vu3'); - // vu2 = game.add.sprite(400, 150, 'vu3'); - // vu3 = game.add.sprite(400, 200, 'vu3'); - // vu4 = game.add.sprite(400, 250, 'vu3'); - - module = new Protracker(); -// module.buffer = game.cache.getBinary('globaltrash'); - module.buffer = game.cache.getBinary('macrocosm'); - module.parse(); - module.play(); - - r1 = new Phaser.Rectangle(400, 100, 100, 32); - r2 = new Phaser.Rectangle(400, 150, 100, 32); - r3 = new Phaser.Rectangle(400, 200, 100, 32); - r4 = new Phaser.Rectangle(400, 250, 100, 32); - - // console.log(module.sample); - -} - -function update() { - - sampleName1 = ''; - sampleName2 = ''; - sampleName3 = ''; - sampleName4 = ''; - - sample1 = module.channel[0].sample; - sample2 = module.channel[1].sample; - sample3 = module.channel[2].sample; - sample4 = module.channel[3].sample; - - /* - module.sample = array of Objects containing: - - data (Float32Array) - finetime - length (ms? bytes?) - looplength - loopstart - name - volume - -arpeggio: 0 -command: 0 -data: 0 -flags: 0 -note: 22 -noteon: 1 -period: 240 -sample: 11 -samplepos: 314.3411880952386 -samplespeed: 0.335118537414966 -semitone: 14 -slidespeed: 0 -slideto: 214 -slidetospeed: 0 -vibratodepth: 0 -vibratopos: 0 -vibratospeed: 0 -vibratowave: 0 -voiceperiod: 240 -volume: 64 - */ - - if (module.sample[sample1]) - { - sampleName1 = module.sample[sample1].name; - } - - if (module.sample[sample2]) - { - sampleName2 = module.sample[sample2].name; - } - - if (module.sample[sample3]) - { - sampleName3 = module.sample[sample3].name; - } - - if (module.sample[sample4]) - { - sampleName4 = module.sample[sample4].name; - } - - // vu1.width = Math.round(module.vu[0] * 400); - // vu2.width = Math.round(module.vu[1] * 400); - // vu3.width = Math.round(module.vu[2] * 400); - // vu4.width = Math.round(module.vu[3] * 400); - - r1.width = Math.round(module.vu[0] * 500); - r2.width = Math.round(module.vu[1] * 500); - r3.width = Math.round(module.vu[2] * 500); - r4.width = Math.round(module.vu[3] * 500); - -} - -function render() { - - game.debug.text('Sample ' + sample1 + ' : ' + sampleName1, 16, 32); - game.debug.text('Sample ' + sample2 + ' : ' + sampleName2, 16, 64); - game.debug.text('Sample ' + sample3 + ' : ' + sampleName3, 16, 96); - game.debug.text('Sample ' + sample4 + ' : ' + sampleName4, 16, 128); - - game.debug.text('Position: ' + module.position, 16, 160); - game.debug.text('Pattern: ' + module.row, 16, 192); - game.debug.text('BPM: ' + module.bpm, 16, 224); - game.debug.text('Speed: ' + module.speed, 16, 256); - game.debug.text('Name: ' + module.title, 16, 288); - game.debug.text('Author: ' + module.signature, 16, 320); - - game.debug.text('vu1: ' + module.vu[0], 16, 352); - game.debug.text('vu2: ' + module.vu[1], 16, 384); - game.debug.text('vu3: ' + module.vu[2], 16, 416); - game.debug.text('vu4: ' + module.vu[3], 16, 448); - - game.debug.geom(r1); - game.debug.geom(r2); - game.debug.geom(r3); - game.debug.geom(r4); - -} diff --git a/examples/wip/misc/mouse scale.js b/examples/wip/misc/mouse scale.js deleted file mode 100644 index cc0fbfa7c..000000000 --- a/examples/wip/misc/mouse scale.js +++ /dev/null @@ -1,68 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // Enable scaling - game.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; - game.stage.scale.maxWidth = 1500; - game.stage.scale.maxHeight = 1000; - game.stage.scale.refresh(); - - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('atari2', 'assets/sprites/atari800xl.png'); - game.load.image('atari4', 'assets/sprites/atari800.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - game.load.image('duck', 'assets/sprites/darkwing_crazy.png'); - game.load.image('firstaid', 'assets/sprites/firstaid.png'); - game.load.image('diamond', 'assets/sprites/diamond.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -function create() { - - game.world.setBounds(0, 0, 2000, 2000); - - // This returns an array of all the image keys in the cache - var images = game.cache.getImageKeys(); - - // Now let's create some random sprites and enable them all for drag and 'bring to top' - for (var i = 0; i < 200; i++) - { - var img = game.rnd.pick(images); - var tempSprite = game.add.sprite(game.world.randomX, game.world.randomY, img); - tempSprite.inputEnabled = true; - tempSprite.input.enableDrag(false, true); - } - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - -} - -function render() { - - game.debug.inputInfo(32, 32); - -} \ No newline at end of file diff --git a/examples/wip/misc/moveToPointer.js b/examples/wip/misc/moveToPointer.js deleted file mode 100644 index 865825c9d..000000000 --- a/examples/wip/misc/moveToPointer.js +++ /dev/null @@ -1,38 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('arrow', 'assets/sprites/arrow.png'); - -} - -var sprite; -var tween; - -function create() { - - sprite = game.add.sprite(32, 32, 'arrow'); - - sprite.anchor.setTo(0.5, 0.5); - - game.input.onDown.add(moveSprite, this); - -} - -function moveSprite (pointer) { - - if (tween && tween.isRunning) - { - tween.stop(); - } - - sprite.rotation = game.physics.angleToPointer(sprite, pointer); - - // 300 = 300 pixels per second = the speed the sprite will move at, regardless of the distance it has to travel - var duration = (game.physics.distanceToPointer(sprite, pointer) / 300) * 1000; - - tween = game.add.tween(sprite).to({ x: pointer.x, y: pointer.y }, duration, Phaser.Easing.Linear.None, true); - -} - diff --git a/examples/wip/misc/multiball.js b/examples/wip/misc/multiball.js deleted file mode 100644 index 08bea5519..000000000 --- a/examples/wip/misc/multiball.js +++ /dev/null @@ -1,40 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.spritesheet('spinner', 'assets/sprites/bluemetal_32x32x4.png', 32, 32); - -} - -var sprites; - -function create() { - - // Here we create a group, populate it with sprites, give them all a random velocity - // and then check the group against itself for collision - - sprites = game.add.group(); - - for (var i = 0; i < 30; i++) - { - var s = sprites.create(game.rnd.integerInRange(100, 700), game.rnd.integerInRange(32, 200), 'spinner'); - s.animations.add('spin', [0,1,2,3]); - s.play('spin', 20, true); - s.body.velocity.x = game.rnd.integerInRange(-200, 200); - s.body.velocity.y = game.rnd.integerInRange(-200, 200); - } - - sprites.setAll('body.collideWorldBounds', true); - sprites.setAll('body.bounce.x', 1); - sprites.setAll('body.bounce.y', 1); - sprites.setAll('body.linearDamping', 0); - sprites.setAll('body.minBounceVelocity', 0); - -} - -function update() { - - game.physics.collide(sprites); - -} diff --git a/examples/wip/misc/nested groups.js b/examples/wip/misc/nested groups.js deleted file mode 100644 index cf5902df2..000000000 --- a/examples/wip/misc/nested groups.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('ball', 'assets/sprites/pangball.png'); - game.load.image('arrow', 'assets/sprites/asteroids_ship.png'); - -} - -var ballsGroup; -var shipsGroup; - -function create() { - - ballsGroup = game.add.group(); - shipsGroup = game.add.group(); - - for (var i = 0; i < 20; i++) - { - // Create some randomly placed sprites in both Groups - ballsGroup.create(game.rnd.integerInRange(0, 128), game.world.randomY, 'ball'); - shipsGroup.create(game.rnd.integerInRange(0, 128), game.world.randomY, 'arrow'); - } - - // Now make the ships group a child of the balls group - so anything that happens to the balls group - // will happen to the ships group too - ballsGroup.add(shipsGroup); - -} - -function update() { - - ballsGroup.x += 0.1; - - // Because shipsGroup is a child of ballsGroup it has already been moved 0.1px by the line above - // So the following line of code will make it appear to move twice as fast as ballsGroup - shipsGroup.x += 0.1; - -} - diff --git a/examples/wip/misc/offset.js b/examples/wip/misc/offset.js deleted file mode 100644 index f64dcfe24..000000000 --- a/examples/wip/misc/offset.js +++ /dev/null @@ -1,33 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - -} - -var sprite1; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - sprite1 = game.add.sprite(350, 300, 'atari'); - sprite1.name = 'atari'; - sprite1.anchor.setTo(0.5, -2); - -} - -function update() { - - sprite1.angle += 1; - -} - - -function render() { - - game.debug.spriteCorners(sprite1); - -} - diff --git a/examples/wip/misc/one way collision.js b/examples/wip/misc/one way collision.js deleted file mode 100644 index c2cb73c30..000000000 --- a/examples/wip/misc/one way collision.js +++ /dev/null @@ -1,325 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - game.load.image('atari', 'assets/sprites/atari130xe.png'); - -} - -var sprite; -var sprite2; -var sprite3; -var reverse = false; - -function onBeginContact(a, b) { - console.log('Begin Contact between', a.name, 'and', b.name); -} - -function onEndContact(a, b) { - console.log('End Contact between', a.name, 'and', b.name); -} - -function create() { - - game.stage.backgroundColor = '#124184'; - - test8(); - -} - -function test8() { - - // A up into B - - sprite = game.add.sprite(300, 200, 'atari'); - sprite.name = 'atari'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(1, 1); - sprite.body.checkCollision.up = false; - sprite.body.checkCollision.down = false; - - sprite2 = game.add.sprite(350, 400, 'gameboy', 2); - sprite2.name = 'gameboy'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(1, 1); - - sprite2.events.onBeginContact.add(onBeginContact, this); - sprite2.events.onEndContact.add(onEndContact, this); - - reverse = true; - - game.input.onDown.add(launch8, this); - -} - -function launch8() { - - sprite2.body.velocity.x = -100; - sprite2.body.velocity.y = -200; - -} - -function test7() { - - // A down into B - - sprite = game.add.sprite(300, 400, 'atari'); - sprite.name = 'atari'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(1, 1); - sprite.body.checkCollision.up = false; - - sprite2 = game.add.sprite(350, 100, 'gameboy', 2); - sprite2.name = 'gameboy'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(1, 1); - - // reverse = true; - - game.input.onDown.add(launch7, this); - -} - -function launch7() { - - sprite2.body.velocity.y = 100; - -} - -function test6() { - - // Offset Down Collision false - - sprite = game.add.sprite(100, 300, 'atari'); - sprite.name = 'atari'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(1, 1); - sprite.body.checkCollision.left = false; - sprite.body.checkCollision.right = false; - - sprite2 = game.add.sprite(500, 330, 'gameboy', 2); - // sprite2 = game.add.sprite(500, 530, 'gameboy', 2); - sprite2.name = 'gameboy'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(1, 1); - - sprite3 = game.add.sprite(400, 100, 'gameboy', 0); - sprite3.name = 'gameboy2'; - sprite3.body.collideWorldBounds = true; - sprite3.body.bounce.setTo(1, 1); - - game.input.onDown.add(launch6, this); - -} - -function launch6() { - - sprite.body.velocity.x = 100; - sprite2.body.velocity.x = -100; - sprite3.body.velocity.y = 100; - -} - -function test5() { - - // Offset Down Collision false - - sprite = game.add.sprite(360, 400, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - // sprite.body.bounce.setTo(0.9, 0.9); - sprite.body.checkCollision.up = false; - - sprite2 = game.add.sprite(400, 200, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - // sprite2.body.checkCollision.down = false; - // sprite2.body.mass = 1; - sprite2.body.bounce.setTo(1, 1); - // sprite2.body.linearDamping = 0; - - game.input.onDown.add(launch5, this); - -} - -function launch5() { - - // sprite.body.velocity.x = 200; - // sprite.body.velocity.y = -300; - // sprite2.body.velocity.x = -200; - sprite2.body.velocity.y = 200; - -} - -function test4() { - - // Down Collision false - - sprite = game.add.sprite(400, 400, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.9, 0.9); - - sprite2 = game.add.sprite(400, 200, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.checkCollision.down = false; - // sprite2.body.mass = 1; - // sprite2.body.bounce.setTo(1, 1); - // sprite2.body.linearDamping = 0; - - game.input.onDown.add(launch4, this); - -} - -function launch4() { - - // sprite.body.velocity.x = 200; - sprite.body.velocity.y = -300; - // sprite2.body.velocity.x = -200; - // sprite2.body.velocity.y = -200; - -} - -function test3() { - - // Top Collision false - - sprite = game.add.sprite(400, 400, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.checkCollision.up = false; - - sprite2 = game.add.sprite(400, 200, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - // sprite2.body.checkCollision.left = false; - sprite2.body.bounce.setTo(0.9, 0.9); - // sprite2.body.mass = 1; - // sprite2.body.bounce.setTo(1, 1); - // sprite2.body.linearDamping = 0; - - game.input.onDown.add(launch3, this); - -} - -function launch3() { - - // sprite.body.velocity.x = 200; - // sprite.body.velocity.y = -300; - // sprite2.body.velocity.x = -200; - sprite2.body.velocity.y = 200; - -} - -function test2() { - - // Left Collision false - - sprite = game.add.sprite(200, 300, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - // sprite.body.checkCollision.right = false; - sprite.body.bounce.setTo(0.9, 0.9); - // sprite.body.linearDamping = 0; - // sprite.scale.setTo(2, 2); - // sprite.body.mass = 2; - - sprite2 = game.add.sprite(500, 300, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.checkCollision.left = false; - // sprite2.body.bounce.setTo(0.9, 0.9); - // sprite2.body.mass = 1; - // sprite2.body.bounce.setTo(1, 1); - // sprite2.body.linearDamping = 0; - - game.input.onDown.add(launch2, this); - -} - -function launch2() { - - sprite.body.velocity.x = 200; - // sprite.body.velocity.y = -300; - // sprite2.body.velocity.x = -200; - // sprite2.body.velocity.y = -200; - -} - - -function test1() { - - // Right Collision false - - sprite = game.add.sprite(200, 300, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.checkCollision.right = false; - // sprite.body.bounce.setTo(0.9, 0.9); - // sprite.body.bounce.setTo(1, 1); - // sprite.body.linearDamping = 0; - // sprite.scale.setTo(2, 2); - // sprite.body.mass = 2; - - sprite2 = game.add.sprite(500, 300, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - sprite2.body.bounce.setTo(0.9, 0.9); - // sprite2.body.mass = 1; - // sprite2.body.bounce.setTo(1, 1); - // sprite2.body.linearDamping = 0; - - game.input.onDown.add(launch1, this); - -} - -function launch1() { - - sprite2.body.velocity.x = -200; - -} - -function update() { - - if (reverse) - { - game.physics.collide(sprite2, sprite); - } - else - { - game.physics.collide(sprite, sprite2); - } - - if (sprite3) - { - game.physics.collide(sprite, sprite3); - } - -} - -function render() { - - if (sprite) - { - game.debug.bodyInfo(sprite, 16, 24); - } - - if (sprite) - { - game.debug.physicsBody(sprite.body); - } - - if (sprite2) - { - game.debug.physicsBody(sprite2.body); - } - - if (sprite3) - { - game.debug.physicsBody(sprite3.body); - } - -} diff --git a/examples/wip/misc/pausetime.js b/examples/wip/misc/pausetime.js deleted file mode 100644 index 89d9eaf23..000000000 --- a/examples/wip/misc/pausetime.js +++ /dev/null @@ -1,31 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, render: render }); - -function create() { - - console.log('game started at ' + this.time.now); - - game.onPause.add(onGamePause, this); - game.onResume.add(onGameResume, this); - -} - -function onGamePause() { - - console.log('game paused at ' + this.time.now); - -} - -function onGameResume() { - - console.log('game un-paused at ' + this.time.now); - console.log('was paused for ' + game.time.pauseDuration); - -} - -function render() { - - game.debug.text('now: ' + game.time.now, 32, 32); - game.debug.text('paused: ' + game.paused, 32, 64); - -} diff --git a/examples/wip/misc/physics-motion.js b/examples/wip/misc/physics-motion.js deleted file mode 100644 index 7d4b2b0d0..000000000 --- a/examples/wip/misc/physics-motion.js +++ /dev/null @@ -1,63 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('chunk', 'assets/sprites/chunk.png'); - game.load.image('arrow', 'assets/sprites/asteroids_ship.png'); - -} - -var sprite; -var bmd; - -function create() { - - game.stage.backgroundColor = '#124184'; - - bmd = game.add.bitmapData(800, 600); - bmd.fillStyle('#ffffff'); - var bg = game.add.sprite(0, 0, bmd); - bg.body.moves = false; - - game.physics.gravity.y = 100; - - sprite = game.add.sprite(32, 450, 'arrow'); - sprite.anchor.setTo(0.5, 0.5); - - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(0.8, 0.8); - - sprite.body.linearDamping = 0.1; - - game.input.onDown.add(launch, this); - -} - -function launch() { - - if (game.input.x < 400) - { - sprite.body.velocity.setTo(-200, -200); - } - else - { - sprite.body.velocity.setTo(200, -200); - } - -} - -function update() { - - sprite.rotation = sprite.body.angle; - - bmd.fillStyle('#ffff00'); - bmd.fillRect(sprite.x, sprite.y, 2, 2); - -} - -function render() { - - game.debug.bodyInfo(sprite, 16, 24); - -} diff --git a/examples/wip/misc/pivot.js b/examples/wip/misc/pivot.js deleted file mode 100644 index 566fa3a33..000000000 --- a/examples/wip/misc/pivot.js +++ /dev/null @@ -1,46 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('ball', 'assets/sprites/pangball.png'); - -} - -var sprite1; -// var sprite2; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - sprite1 = game.add.sprite(300, 300, 'ball'); - - sprite1.anchor.setTo(0, 1); - sprite1.pivot.x = 100; - sprite1.pivot.y = 100; - - // sprite2 = game.add.sprite(0, 0, 'mushroom'); - // sprite2.name = 'mushroom'; - -} - -function update() { - - sprite1.angle += 1; - // sprite1.pivot.x = game.input.x; - // sprite1.pivot.y = game.input.y; - -} - -function render() { - - game.debug.pixel(sprite1.pivot.x, sprite1.pivot.y); - - // game.debug.spriteInfo(sprite1, 100, 400); - // game.debug.spriteBounds(sprite1); - // game.debug.spriteInfo(sprite2, 100, 100); - // game.debug.spriteBounds(sprite2); -} - diff --git a/examples/wip/misc/pixelpick atlas trimmed.js b/examples/wip/misc/pixelpick atlas trimmed.js deleted file mode 100644 index 47bfc6d54..000000000 --- a/examples/wip/misc/pixelpick atlas trimmed.js +++ /dev/null @@ -1,51 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.atlas('atlas', 'assets/sprites/atlas_json_array_trimmed.png', 'assets/sprites/atlas_json_array_trimmed.json'); - -} - -var wizball; -// var chick; -// var mech; -// var robot; -// var cop; - -function create() { - - game.stage.backgroundColor = '#404040'; - - // This demonstrates pixel perfect click detection even if using sprites in a texture atlas. - - // chick = game.add.sprite(64, 64, 'atlas'); - // chick.frameName = 'budbrain_chick.png'; - // chick.inputEnabled = true; - // chick.input.pixelPerfect = true; - // chick.input.useHandCursor = true; - - // cop = game.add.sprite(600, 64, 'atlas'); - // cop.frameName = 'ladycop.png'; - // cop.inputEnabled = true; - // cop.input.pixelPerfect = true; - // cop.input.useHandCursor = true; - - // robot = game.add.sprite(50, 300, 'atlas'); - // robot.frameName = 'robot.png'; - // robot.inputEnabled = true; - // robot.input.pixelPerfect = true; - // robot.input.useHandCursor = true; - - wizball = game.add.sprite(100, 400, 'atlas', 'wizball'); - wizball.inputEnabled = true; - wizball.input.pixelPerfect = true; - wizball.input.useHandCursor = true; - - // mech = game.add.sprite(250, 100, 'atlas'); - // mech.frameName = 'titan_mech.png'; - // mech.inputEnabled = true; - // mech.input.pixelPerfect = true; - // mech.input.useHandCursor = true; - -} diff --git a/examples/wip/misc/platform.js b/examples/wip/misc/platform.js deleted file mode 100644 index 2a541a85d..000000000 --- a/examples/wip/misc/platform.js +++ /dev/null @@ -1,121 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/platform.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('platformer_tiles', 'assets/tilemaps/tiles/platformer_tiles.png'); - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - game.load.spritesheet('balls', 'assets/sprites/balls.png', 17, 17); - -} - -var map; -var layer; -var sprite; -var sprite2; -var balls; -var cursors; - -function create() { - - game.stage.backgroundColor = '#124184'; - - map = game.add.tilemap('map'); - - map.addTilesetImage('platformer_tiles'); - - map.setCollisionBetween(21, 53); - - layer = map.createLayer('Tile Layer 1'); - - layer.debug = true; - - // game.physics.gravity.y = 150; - -/* - balls = game.add.group(); - - for (var i = 0; i < 30; i++) - { - var s = balls.create(game.rnd.integerInRange(100, 700), game.rnd.integerInRange(100, 200), 'balls', game.rnd.integerInRange(0, 6)); - s.body.velocity.x = game.rnd.integerInRange(-400, 400); - s.body.velocity.y = game.rnd.integerInRange(-100, -200); - s.name = 'ball' + i; - } - - balls.setAll('body.collideWorldBounds', true); - balls.setAll('body.bounce.x', 0.8); - balls.setAll('body.bounce.y', 0.9); - balls.setAll('body.minBounceVelocity', 0.9); - balls.setAll('body.linearDamping', 0.5); -*/ - - sprite2 = game.add.sprite(340, 250, 'gameboy', 2); - sprite2.name = 'green'; - sprite2.body.collideWorldBounds = true; - // sprite2.body.bounce.setTo(0.5, 0.5); - - sprite = game.add.sprite(270, 100, 'gameboy', 0); - sprite.name = 'red'; - sprite.body.collideWorldBounds = true; - sprite.body.minBounceVelocity = 0.9; - sprite.body.bounce.setTo(0.5, 0.9); - sprite.body.linearDamping = 0.5; - - - game.input.onDown.add(launch, this); - -} - -function launch() { - - // sprite.body.velocity.x = -200; - // sprite.body.velocity.y = -200; - - sprite2.body.velocity.x = -200; - sprite2.body.velocity.y = -200; - -} - -function hit(face, body1, body2) { - - console.log('hit', face); - -} - -var flag = false; - -function update() { - - // game.physics.collide(balls, layer); - game.physics.collide(sprite, layer); - game.physics.collide(sprite2, layer); - game.physics.collide(sprite, sprite2); - -} - -function render() { - - game.debug.bodyInfo(sprite2, 32, 32); - game.debug.physicsBody(sprite2.body); - - - // game.debug.text(sprite2.body.left, 32, 30); - // game.debug.text(sprite2.body.right, 32, 50); - // game.debug.text(sprite2.body.top, 32, 70); - // game.debug.text(sprite2.body.bottom, 32, 90); - - - // for (var i = 0; i < balls._container.length; i++) - // { - - // } - - // if (sprite) - // { - // // game.debug.bodyInfo(sprite, 20, 30); - // game.debug.bodyInfo(sprite2, 20, 230); - // } - -} \ No newline at end of file diff --git a/examples/wip/misc/prerend.js b/examples/wip/misc/prerend.js deleted file mode 100644 index d3775f5a9..000000000 --- a/examples/wip/misc/prerend.js +++ /dev/null @@ -1,16 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('test', 'assets/pics/nanoha_taiken_blue.png'); - -} - -function create() { - - game.stage.backgroundColor = 'rgba(0,0,0,0.3)'; - - game.add.sprite(0, 0, 'test'); - -} diff --git a/examples/wip/misc/pt.js b/examples/wip/misc/pt.js deleted file mode 100644 index 007fa11fa..000000000 --- a/examples/wip/misc/pt.js +++ /dev/null @@ -1,913 +0,0 @@ -/* - amiga protracker module player for web audio api - (c) 2012-2013 firehawk/tda (firehawk@haxor.fi) - - originally hacked together in a weekend, so please excuse - me for the spaghetti code. :) - - AMIGAAAAAAAAH!! - - kinda sorta changelog: - (apr 2013) - - changed the logic for pattern break/jump. mod.pattern_skank now - plays correctly. - (feb 2013) - - fixed NaN samples with mod.fractured and mod.multicolour (thanks Aegis!) - (jan 2013) - - fixed vibrato amplitude (was half of what it should be, apparently) - - fixed to work on safari again (thanks Matt Diamond @ stackoverflow.com) - (dec 2012) - - replaced effect switch-statement with jumptables - - fixed clicks (bad loops, empty samples) - - fixed playback bug with sample-only rows - - added amiga 500 lowpass filters (not 100% authentic, though) - - added compressor to output - - latest safari has broken web audio so chrome-only for now - (aug 2012) - - first version written from scratch - - todo: - - safari on ipad is broken again, it seems - - fix more playback bugs - * mod.black_queen (pattern loop has glitches) - - properly test EEx delay pattern - - implement the rest of the effects - - optimize for more speed!! SPEEEED!! - * switch to fixed point sample pointers, Math.floor() is _slow_ on iOS -*/ - -// constructor for protracker player object -function Protracker() -{ - var i, t; - - this.initialize(); - this.clearsong(); - - this.url=""; - this.loading=false; - this.ready=false; - this.playing=false; - this.buffer=0; - this.mixerNode=0; - this.paused=false; - this.repeat=false; - this.separation=true; - - this.palclock=true; - - this.autostart=false; - - this.onReady=function(){}; - this.onPlay=function(){}; - this.onStop=function(){}; - - // paula period values - this.baseperiodtable=new Array( - 856,808,762,720,678,640,604,570,538,508,480,453, - 428,404,381,360,339,320,302,285,269,254,240,226, - 214,202,190,180,170,160,151,143,135,127,120,113); - - // finetune multipliers - this.finetunetable=new Array(); - for(t=0;t<16;t++) this.finetunetable[t]=Math.pow(2, (t-8)/12/8); - - // calc tables for vibrato waveforms - this.vibratotable=new Array(); - for(t=0;t<4;t++) { - this.vibratotable[t]=new Array(); - for(i=0;i<64;i++) { - switch(t) { - case 0: - this.vibratotable[t][i]=127*Math.sin(Math.PI*2*(i/64)); - break; - case 1: - this.vibratotable[t][i]=127-4*i; - break; - case 2: - this.vibratotable[t][i]=(i<32)?127:-127; - break; - case 3: - this.vibratotable[t][i]=(1-2*Math.random())*127; - break; - } - } - } - - // effect jumptables - this.effects_t0 = new Array( - this.effect_t0_0, this.effect_t0_1, this.effect_t0_2, this.effect_t0_3, this.effect_t0_4, this.effect_t0_5, this.effect_t0_6, this.effect_t0_7, - this.effect_t0_8, this.effect_t0_9, this.effect_t0_a, this.effect_t0_b, this.effect_t0_c, this.effect_t0_d, this.effect_t0_e, this.effect_t0_f); - this.effects_t0_e = new Array( - this.effect_t0_e0, this.effect_t0_e1, this.effect_t0_e2, this.effect_t0_e3, this.effect_t0_e4, this.effect_t0_e5, this.effect_t0_e6, this.effect_t0_e7, - this.effect_t0_e8, this.effect_t0_e9, this.effect_t0_ea, this.effect_t0_eb, this.effect_t0_ec, this.effect_t0_ed, this.effect_t0_ee, this.effect_t0_ef); - this.effects_t1 = new Array( - this.effect_t1_0, this.effect_t1_1, this.effect_t1_2, this.effect_t1_3, this.effect_t1_4, this.effect_t1_5, this.effect_t1_6, this.effect_t1_7, - this.effect_t1_8, this.effect_t1_9, this.effect_t1_a, this.effect_t1_b, this.effect_t1_c, this.effect_t1_d, this.effect_t1_e, this.effect_t1_f); - this.effects_t1_e = new Array( - this.effect_t1_e0, this.effect_t1_e1, this.effect_t1_e2, this.effect_t1_e3, this.effect_t1_e4, this.effect_t1_e5, this.effect_t1_e6, this.effect_t1_e7, - this.effect_t1_e8, this.effect_t1_e9, this.effect_t1_ea, this.effect_t1_eb, this.effect_t1_ec, this.effect_t1_ed, this.effect_t1_ee, this.effect_t1_ef); - - this.context = null; - this.samplerate=44100; - this.bufferlen=2048; -} - - - -// create the web audio context -Protracker.prototype.createContext = function() -{ - this.context = new webkitAudioContext(); - this.samplerate=this.context.sampleRate; - this.bufferlen=(this.samplerate > 44100) ? 4096 : 2048; - - // fixed filter at 6kHz - this.filterNode=this.context.createBiquadFilter(); - this.filterNode.frequency.value=6000 - - // "LED filter" at 3.5kHz - off by default - this.lowpassNode=this.context.createBiquadFilter(); - this.lowpassNode.frequency.value=28867; - - // mixer - this.mixerNode=this.context.createJavaScriptNode(this.bufferlen, 1, 2); - this.mixerNode.module=this; - this.mixerNode.onaudioprocess=Protracker.prototype.mix; - - // compressor for a bit of volume boost - this.compressorNode=this.context.createDynamicsCompressor(); - - // patch up some cables :) - this.mixerNode.connect(this.filterNode); - this.filterNode.connect(this.lowpassNode); - this.lowpassNode.connect(this.compressorNode); - this.compressorNode.connect(this.context.destination); -} - - - -// play loaded and parsed module with webaudio context -Protracker.prototype.play = function() -{ - if (this.context==null) this.createContext(); - - if (!this.ready) return false; - if (this.paused) { - this.paused=false; - return true; - } - this.paused=false; - this.initialize(); - this.flags=1+2; - this.playing=true; - this.onPlay(); - return true; -} - - - -// pause playback -Protracker.prototype.pause = function() -{ - if (!this.paused) { - this.paused=true; - } else { - this.paused=false; - } -} - - - -// stop playback and release webaudio node -Protracker.prototype.stop = function() -{ - this.playing=false; - this.onStop(); -} - - - -// jump positions forward/back -Protracker.prototype.jump = function(step) -{ - this.tick=0; - this.row=0; - this.position+=step; - this.flags=1+2; - if (this.position<0) this.position=0; - if (this.position >= this.songlen) this.stop(); -} - - - -// set whether module repeats after songlen -Protracker.prototype.setrepeat = function(rep) -{ - this.repeat=rep; -} - - - -// set stereo separation mode (false=paula, true=betterpaula) -Protracker.prototype.setseparation = function(sep) -{ - this.separation=sep; -} - - - -// set amiga video standard (false=NTSC, true=PAL) -Protracker.prototype.setamigatype = function(clock) -{ - this.palclock=clock; -} - - - -// set autostart to play immediately after loading -Protracker.prototype.setautostart = function(st) -{ - this.autostart=st; -} - - - -// clear song data -Protracker.prototype.clearsong = function() -{ - this.title=""; - this.signature=""; - this.songlen=1; - this.repeatpos=0; - this.patterntable=new ArrayBuffer(128); - for(i=0;i<128;i++) this.patterntable[i]=0; - - this.channels=4; - - this.sample=new Array(); - this.samples=31; - for(i=0;i<31;i++) { - this.sample[i]=new Object(); - this.sample[i].name=""; - this.sample[i].length=0; - this.sample[i].finetune=0; - this.sample[i].volume=64; - this.sample[i].loopstart=0; - this.sample[i].looplength=0; - this.sample[i].data=0; - } - - this.patterns=0; - this.pattern=new Array(); - this.note=new Array(); - - this.looprow=0; - this.loopstart=0; - this.loopcount=0; - - this.patterndelay=0; - this.patternwait=0; -} - - -// initialize all player variables -Protracker.prototype.initialize = function() -{ - this.tick=0; - this.position=0; - this.row=0; - this.offset=0; - this.flags=0; - - this.speed=6; - this.bpm=125; - this.breakrow=0; - this.patternjump=0; - this.patterndelay=0; - this.patternwait=0; - - this.channel=new Array(); - for(i=0;i0x1f) && (this.buffer[st+j]<0x7f)) ? - (String.fromCharCode(this.buffer[st+j])) : - (" "); - j++; - } - this.sample[i].length=2*(this.buffer[st+22]*256 + this.buffer[st+23]); - this.sample[i].finetune=this.buffer[st+24]; - if (this.sample[i].finetune > 7) this.sample[i].finetune=this.sample[i].finetune-16; - this.sample[i].volume=this.buffer[st+25]; - this.sample[i].loopstart=2*(this.buffer[st+26]*256 + this.buffer[st+27]); - this.sample[i].looplength=2*(this.buffer[st+28]*256 + this.buffer[st+29]); - if (this.sample[i].looplength==2) this.sample[i].looplength=0; - if (this.sample[i].loopstart>this.sample[i].length) { - this.sample[i].loopstart=0; - this.sample[i].looplength=0; - } - } - - this.songlen=this.buffer[950]; - if (this.buffer[951] != 127) this.repeatpos=this.buffer[951]; - for(i=0;i<128;i++) { - this.patterntable[i]=this.buffer[952+i]; - if (this.patterntable[i] > this.patterns) this.patterns=this.patterntable[i]; - } - this.patterns+=1; - var patlen=4*64*this.channels; - - this.pattern=new Array(); - this.note=new Array(); - for(i=0;ispd) { mod.tick++; mod.offset=0; mod.flags|=1; } - if (mod.tick>=mod.speed) { - - if (mod.patterndelay) { // delay pattern - if (mod.tick < ((mod.patternwait+1)*mod.speed)) { - mod.patternwait++; - } else { - mod.row++; mod.tick=0; mod.flags|=2; mod.patterndelay=0; - - } - } - else { - - if (mod.flags&(16+32+64)) { - if (mod.flags&64) { // loop pattern? - mod.row=mod.looprow; - mod.flags&=0xa1; - mod.flags|=2; - } - else { - if (mod.flags&16) { // pattern jump/break? - //console.log("break to pattern " + mod.patternjump + " row "+mod.breakrow); - mod.position=mod.patternjump; - mod.row=mod.breakrow; - mod.patternjump=0; - mod.breakrow=0; - mod.flags&=0xe1; - mod.flags|=2; - } - } - mod.tick=0; - } else { - mod.row++; mod.tick=0; mod.flags|=2; - } - } - } - - if (mod.row>=64) { mod.position++; mod.row=0; mod.flags|=4; } - if (mod.position>=mod.songlen) { - if (mod.repeat) { - mod.position=0; - } else { - mod.stop(); - } - return; - } -} - - - -// mix an audio buffer with data -Protracker.prototype.mix = function(ape) { - var f; - var p, pp, n, nn; - var mod=ape.srcElement.module; - outp=new Array(); - - var bufs=new Array(ape.outputBuffer.getChannelData(0), ape.outputBuffer.getChannelData(1)); - var buflen=ape.outputBuffer.length; - for(var s=0;s3) mod.channel[ch].vibratopos=0; - mod.channel[ch].flags|=3; // recalc speed - mod.channel[ch].noteon=1; - } else { - mod.channel[ch].slideto=n; - - } - } - nn=mod.pattern[p][pp+0]&0xf0 | mod.pattern[p][pp+2]>>4; - if (nn) { - mod.channel[ch].sample=nn-1; - - mod.channel[ch].volume=mod.sample[nn-1].volume; - if (!n && (mod.channel[ch].samplepos > mod.sample[nn-1].length)) mod.channel[ch].samplepos=0; - } - } - } - mod.channel[ch].voiceperiod=mod.channel[ch].period; - if (mod.channel[ch].samplepos==0) modsample[ch]=mod.channel[ch].sample; - - - // kill empty samples - if (!mod.sample[mod.channel[ch].sample].length) mod.channel[ch].noteon=0; - - // effects - if (mod.flags&1) { - if (!mod.tick) { - // process only on tick 0 - mod.effects_t0[mod.channel[ch].command](mod, ch); - } else { - mod.effects_t1[mod.channel[ch].command](mod, ch); - } - } - - // recalc note number from period - if (mod.channel[ch].flags&2) { - for(var np=0; np=mod.channel[ch].period) mod.channel[ch].note=np; - mod.channel[ch].semitone=7; - if (mod.channel[ch].period>=120) - mod.channel[ch].semitone=mod.baseperiodtable[mod.channel[ch].note]-mod.baseperiodtable[mod.channel[ch].note+1]; - } - - // recalc sample speed and apply finetune - if ((mod.channel[ch].flags&1 || mod.flags&2) && mod.channel[ch].voiceperiod) - mod.channel[ch].samplespeed= - (mod.palclock ? 7093789.2 : 7159090.5)/(mod.channel[ch].voiceperiod*2) * mod.finetunetable[mod.sample[mod.channel[ch].sample].finetune+8] / mod.samplerate; - - // advance vibrato on each new tick - if (mod.flags&1) { - mod.channel[ch].vibratopos+=mod.channel[ch].vibratospeed; - mod.channel[ch].vibratopos&=0x3f; - } - - // mix channel to output - och=och^(ch&1); - f=0.0; - if (mod.channel[ch].noteon) { - if (mod.sample[mod.channel[ch].sample].length > mod.channel[ch].samplepos) - f=(1.0/mod.channels) * - (mod.sample[mod.channel[ch].sample].data[Math.floor(mod.channel[ch].samplepos)]*mod.channel[ch].volume)/64.0; - outp[och]+=f; - mod.channel[ch].samplepos+=mod.channel[ch].samplespeed; - } - if (s==0) mod.vu[ch]=Math.abs(f); - - // loop or end samples - if (mod.channel[ch].noteon) { - if (mod.sample[mod.channel[ch].sample].loopstart || mod.sample[mod.channel[ch].sample].looplength) { - if (mod.channel[ch].samplepos >= (mod.sample[mod.channel[ch].sample].loopstart+mod.sample[mod.channel[ch].sample].looplength)) { - mod.channel[ch].samplepos=mod.sample[mod.channel[ch].sample].loopstart; - } - } else { - if (mod.channel[ch].samplepos >= mod.sample[mod.channel[ch].sample].length) { - mod.channel[ch].noteon=0; - } - } - } - - // clear channel flags - mod.channel[ch].flags=0; - } - mod.offset++; - mod.flags&=0x70; - } - - // a more headphone-friendly stereo separation (aka. betterpaula) - if (mod.separation) { - t=outp[0]; - outp[0]=outp[0]*0.6 + outp[1]*0.4; - outp[1]=outp[1]*0.6 + t*0.4; - } - bufs[0][s]=outp[0]; - bufs[1][s]=outp[1]; - } -} - - - -// -// tick 0 effect functions -// -Protracker.prototype.effect_t0_0=function(mod, ch) { // 0 arpeggio - mod.channel[ch].arpeggio=mod.channel[ch].data; -} -Protracker.prototype.effect_t0_1=function(mod, ch) { // 1 slide up - if (mod.channel[ch].data) mod.channel[ch].slidespeed=mod.channel[ch].data; -} -Protracker.prototype.effect_t0_2=function(mod, ch) { // 2 slide down - if (mod.channel[ch].data) mod.channel[ch].slidespeed=mod.channel[ch].data; -} -Protracker.prototype.effect_t0_3=function(mod, ch) { // 3 slide to note - if (mod.channel[ch].data) mod.channel[ch].slidetospeed=mod.channel[ch].data; -} -Protracker.prototype.effect_t0_4=function(mod, ch) { // 4 vibrato - if (mod.channel[ch].data&0x0f && mod.channel[ch].data&0xf0) { - mod.channel[ch].vibratodepth=(mod.channel[ch].data&0x0f); - mod.channel[ch].vibratospeed=(mod.channel[ch].data&0xf0)>>4; - } - mod.channel[ch].voiceperiod+= - (mod.channel[ch].vibratodepth/32)*mod.channel[ch].semitone*(mod.vibratotable[mod.channel[ch].vibratowave&3][mod.channel[ch].vibratopos]/127); - mod.channel[ch].flags|=1; -} -Protracker.prototype.effect_t0_5=function(mod, ch) { // 5 -} -Protracker.prototype.effect_t0_6=function(mod, ch) { // 6 -} -Protracker.prototype.effect_t0_7=function(mod, ch) { // 7 -} -Protracker.prototype.effect_t0_8=function(mod, ch) { // 8 -} -Protracker.prototype.effect_t0_9=function(mod, ch) { // 9 set sample offset - mod.channel[ch].samplepos=mod.channel[ch].data*256; -} -Protracker.prototype.effect_t0_a=function(mod, ch) { // a -} -Protracker.prototype.effect_t0_b=function(mod, ch) { // b pattern jump - mod.breakrow=0; - mod.patternjump=mod.channel[ch].data; - mod.flags|=16; -} -Protracker.prototype.effect_t0_c=function(mod, ch) { // c set volume - mod.channel[ch].volume=mod.channel[ch].data; -} -Protracker.prototype.effect_t0_d=function(mod, ch) { // d pattern break - mod.breakrow=((mod.channel[ch].data&0xf0)>>4)*10 + (mod.channel[ch].data&0x0f); - if (!(mod.flags&16)) mod.patternjump=mod.position+1; - mod.flags|=16; -} -Protracker.prototype.effect_t0_e=function(mod, ch) { // e - var i=(mod.channel[ch].data&0xf0)>>4; - mod.effects_t0_e[i](mod, ch); -} -Protracker.prototype.effect_t0_f=function(mod, ch) { // f set speed - if (mod.channel[ch].data > 32) { - mod.bpm=mod.channel[ch].data; - } else { - if (mod.channel[ch].data) mod.speed=mod.channel[ch].data; - } -} - - - -// -// tick 0 effect e functions -// -Protracker.prototype.effect_t0_e0=function(mod, ch) { // e0 filter on/off - if (mod.channel[ch].data&0x0f) { - mod.lowpassNode.frequency.value=4280; //3500; - } else { - mod.lowpassNode.frequency.value=28867; - } -} -Protracker.prototype.effect_t0_e1=function(mod, ch) { // e1 fine slide up - mod.channel[ch].period-=mod.channel[ch].data&0x0f; - if (mod.channel[ch].period < 113) mod.channel[ch].period=113; -} -Protracker.prototype.effect_t0_e2=function(mod, ch) { // e2 fine slide down - mod.channel[ch].period+=mod.channel[ch].data&0x0f; - if (mod.channel[ch].period > 856) mod.channel[ch].period=856; - mod.channel[ch].flags|=1; -} -Protracker.prototype.effect_t0_e3=function(mod, ch) { // e3 set glissando -} -Protracker.prototype.effect_t0_e4=function(mod, ch) { // e4 set vibrato waveform - mod.channel[ch].vibratowave=mod.channel[ch].data&0x07; -} -Protracker.prototype.effect_t0_e5=function(mod, ch) { // e5 set finetune -} -Protracker.prototype.effect_t0_e6=function(mod, ch) { // e6 loop pattern - if (mod.channel[ch].data&0x0f) { - if (mod.loopcount) { - mod.loopcount--; - } else { - mod.loopcount=mod.channel[ch].data&0x0f; - } - if (mod.loopcount) mod.flags|=64; - } else { - mod.looprow=mod.row; - } -} -Protracker.prototype.effect_t0_e7=function(mod, ch) { // e7 -} -Protracker.prototype.effect_t0_e8=function(mod, ch) { // e8 -} -Protracker.prototype.effect_t0_e9=function(mod, ch) { // e9 -} -Protracker.prototype.effect_t0_ea=function(mod, ch) { // ea fine volslide up - mod.channel[ch].volume+=mod.channel[ch].data&0x0f; - if (mod.channel[ch].volume > 64) mod.channel[ch].volume=64; -} -Protracker.prototype.effect_t0_eb=function(mod, ch) { // eb fine volslide down - mod.channel[ch].volume-=mod.channel[ch].data&0x0f; - if (mod.channel[ch].volume < 0) mod.channel[ch].volume=0; -} -Protracker.prototype.effect_t0_ec=function(mod, ch) { // ec -} -Protracker.prototype.effect_t0_ed=function(mod, ch) { // ed delay sample - if (mod.tick==(mod.channel[ch].data&0x0f)) { - // start note - var p=mod.patterntable[mod.position]; - var pp=mod.row*4*mod.channels + ch*4; - n=(mod.pattern[p][pp]&0x0f)<<8 | mod.pattern[p][pp+1]; - if (n) { - mod.channel[ch].period=n; - mod.channel[ch].voiceperiod=mod.channel[ch].period; - mod.channel[ch].samplepos=0; - if (mod.channel[ch].vibratowave>3) mod.channel[ch].vibratopos=0; - mod.channel[ch].flags|=3; // recalc speed - mod.channel[ch].noteon=1; - } - n=mod.pattern[p][pp+0]&0xf0 | mod.pattern[p][pp+2]>>4; - if (n) { - mod.channel[ch].sample=n-1; - mod.channel[ch].volume=mod.sample[n-1].volume; - } - } -} -Protracker.prototype.effect_t0_ee=function(mod, ch) { // ee delay pattern - mod.patterndelay=mod.channel[ch].data&0x0f; - mod.patternwait=0; -} -Protracker.prototype.effect_t0_ef=function(mod, ch) { // ef -} - - - -// -// tick 1+ effect functions -// -Protracker.prototype.effect_t1_0=function(mod, ch) { // 0 arpeggio - if (mod.channel[ch].data) { - var apn=mod.channel[ch].note; - if ((mod.tick%3)==1) apn+=mod.channel[ch].arpeggio>>4; - if ((mod.tick%3)==2) apn+=mod.channel[ch].arpeggio&0x0f; - if (apn>=0 && apn <= mod.baseperiodtable.length) - mod.channel[ch].voiceperiod = mod.baseperiodtable[apn]; - mod.channel[ch].flags|=1; - } -} -Protracker.prototype.effect_t1_1=function(mod, ch) { // 1 slide up - mod.channel[ch].period-=mod.channel[ch].slidespeed; - if (mod.channel[ch].period<113) mod.channel[ch].period=113; - mod.channel[ch].flags|=3; // recalc speed -} -Protracker.prototype.effect_t1_2=function(mod, ch) { // 2 slide down - mod.channel[ch].period+=mod.channel[ch].slidespeed; - if (mod.channel[ch].period>856) mod.channel[ch].period=856; - mod.channel[ch].flags|=3; // recalc speed -} -Protracker.prototype.effect_t1_3=function(mod, ch) { // 3 slide to note - if (mod.channel[ch].period < mod.channel[ch].slideto) { - mod.channel[ch].period+=mod.channel[ch].slidetospeed; - if (mod.channel[ch].period > mod.channel[ch].slideto) - mod.channel[ch].period=mod.channel[ch].slideto; - } - if (mod.channel[ch].period > mod.channel[ch].slideto) { - mod.channel[ch].period-=mod.channel[ch].slidetospeed; - if (mod.channel[ch].period>4); - if (mod.channel[ch].volume>64) mod.channel[ch].volume=64; - } - if (!(mod.channel[ch].data&0xf0)) { - // x is zero, slide down - mod.channel[ch].volume-=(mod.channel[ch].data&0x0f); - if (mod.channel[ch].volume<0) mod.channel[ch].volume=0; - } -} -Protracker.prototype.effect_t1_b=function(mod, ch) { // b pattern jump -} -Protracker.prototype.effect_t1_c=function(mod, ch) { // c set volume -} -Protracker.prototype.effect_t1_d=function(mod, ch) { // d pattern break -} -Protracker.prototype.effect_t1_e=function(mod, ch) { // e - var i=(mod.channel[ch].data&0xf0)>>4; - mod.effects_t1_e[i](mod, ch); -} -Protracker.prototype.effect_t1_f=function(mod, ch) { // f -} - - - -// -// tick 1+ effect e functions -// -Protracker.prototype.effect_t1_e0=function(mod, ch) { // e0 -} -Protracker.prototype.effect_t1_e1=function(mod, ch) { // e1 -} -Protracker.prototype.effect_t1_e2=function(mod, ch) { // e2 -} -Protracker.prototype.effect_t1_e3=function(mod, ch) { // e3 -} -Protracker.prototype.effect_t1_e4=function(mod, ch) { // e4 -} -Protracker.prototype.effect_t1_e5=function(mod, ch) { // e5 -} -Protracker.prototype.effect_t1_e6=function(mod, ch) { // e6 -} -Protracker.prototype.effect_t1_e7=function(mod, ch) { // e7 -} -Protracker.prototype.effect_t1_e8=function(mod, ch) { // e8 -} -Protracker.prototype.effect_t1_e9=function(mod, ch) { // e9 retrig sample - if (mod.tick%(mod.channel[ch].data&0x0f)==0) - mod.channel[ch].samplepos=0; -} -Protracker.prototype.effect_t1_ea=function(mod, ch) { // ea -} -Protracker.prototype.effect_t1_eb=function(mod, ch) { // eb -} -Protracker.prototype.effect_t1_ec=function(mod, ch) { // ec cut sample - if (mod.tick==(mod.channel[ch].data&0x0f)) - mod.channel[ch].volume=0; -} -Protracker.prototype.effect_t1_ed=function(mod, ch) { // ed delay sample - mod.effect_t0_ed(mod, ch); -} -Protracker.prototype.effect_t1_ee=function(mod, ch) { // ee -} -Protracker.prototype.effect_t1_ef=function(mod, ch) { // ef -} diff --git a/examples/wip/misc/rabbit map.js b/examples/wip/misc/rabbit map.js deleted file mode 100644 index 605ed8996..000000000 --- a/examples/wip/misc/rabbit map.js +++ /dev/null @@ -1,251 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/features_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('walls_1x2', 'assets/tilemaps/tiles/walls_1x2.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - - game.load.image('ball', 'assets/sprites/shinyball.png'); - game.load.image('phaser', 'assets/sprites/firstaid.png'); - // game.load.image('phaser', 'assets/sprites/atari130xe.png'); - // game.load.image('phaser', 'assets/sprites/mushroom2.png'); - -} - -var cursors; -var map; -var coins; - -var layer; -var layer2; -var layer3; - -var sprite; -var ball; -var marker; - -function create() { - -console.log(' --- state create start ---'); - - $('#step').click(function(){ - game.step(); - }); - - game.stage.backgroundColor = '#124184'; - - - marker = new Phaser.Line(256, 0, 256, 600); - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('walls_1x2'); - map.addTilesetImage('tiles2'); - - map.setCollisionBetween(1, 12); - - layer = map.createLayer('Tile Layer 1'); - - // layer.debug = true; - - layer.resizeWorld(); - - game.physics.gravity.y = 200; - - - sprite = game.add.sprite(100, 240, 'phaser'); - // sprite.anchor.setTo(0.5, 0.5); - // sprite.body.setCircle(20); - - // sprite.body.moves = false; - - ball = game.add.sprite(200, 180, 'ball'); - - // game.add.tween(sprite).to({x: 500},5000,Phaser.Easing.Linear.None,true); - - // game.add.tween(sprite).to({angle: 360},5000,Phaser.Easing.Linear.None,true); - - // sprite = game.add.sprite(200, 240, 'phaser'); // 3-block corner test - - // sprite.debug = true; - // game.stepping = true; - - // sprite.body.velocity.y = -300; - - // sprite.body.velocity.y = 200; - - - - - - - // We'll set a lower max angular velocity here to keep it from going totally nuts - // sprite.body.maxAngular = 500; - - // Apply a drag otherwise the sprite will just spin and never slow down - // sprite.body.angularDrag = 50; - - // sprite.body.bounce.x = 0.8; - sprite.body.bounce.y = 0.8; - - // sprite.angle = 35; - - game.camera.follow(sprite); - - // game.input.onDown.add(getIt, this); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - -// console.log(' --- state update start ---'); - -/* - if (cursors.left.isDown) - { - game.camera.x -= 1; - } - else if (cursors.right.isDown) - { - game.camera.x += 1; - } - - if (cursors.up.isDown) - { - layer.scrollY -= 4; - } - else if (cursors.down.isDown) - { - layer.scrollY += 4; - } -*/ - - game.physics.collide(sprite, layer); - game.physics.collide(sprite, ball); - - // sprite.body.velocity.y = -300; - - // sprite.body.angularVelocity = -100; - // sprite.body.angularAcceleration = 200; - - - // sprite.body.velocity.x = 0; - // sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - // sprite.body.acceleration.x = 0; - // sprite.body.angularAcceleration = 0; - - if (cursors.left.isDown) - { - // sprite.body.acceleration.x = -200; - sprite.body.angularVelocity = -300; - // sprite.body.angularAcceleration -= 200; - } - else if (cursors.right.isDown) - { - // sprite.body.acceleration.x = 200; - sprite.body.angularVelocity = 300; - // sprite.body.angularAcceleration += 200; - } - - if (cursors.up.isDown) - { - game.physics.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - - - - - /* - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - sprite.angle = sprite.angle + 1; - */ - - // if (cursors.up.isDown) - // { - // sprite.body.velocity.y = -200; - // } - // else if (cursors.down.isDown) - // { - // sprite.body.velocity.y = 100; - // } - - // if (cursors.left.isDown) - // { - // sprite.body.velocity.x = -200; - // } - // else if (cursors.right.isDown) - // { - // sprite.body.velocity.x = 200; - // } - - // if (cursors.up.isDown) - // { - // sprite.y -= 2; - // } - // else if (cursors.down.isDown) - // { - // sprite.y += 2; - // } - - // if (cursors.left.isDown) - // { - // sprite.x -= 2; - // } - // else if (cursors.right.isDown) - // { - // sprite.x += 2; - // } - - // if (cursors.up.isDown) - // { - // sprite.body.y -= 2; - // } - // else if (cursors.down.isDown) - // { - // sprite.body.y += 2; - // } - - // if (cursors.left.isDown) - // { - // sprite.body.x -= 2; - // } - // else if (cursors.right.isDown) - // { - // sprite.body.x += 2; - // } - - - -} - -function render() { - - // game.debug.spriteBody(sprite); - // game.debug.spriteBounds(sprite); - - game.debug.physicsBody(sprite.body); - game.debug.bodyInfo(sprite, 32, 32); - - // game.debug.line(marker, 'rgba(255,255,255,0.5)'); - - // game.debug.text(sprite.deltaX, 32, 32); - // game.debug.text(sprite.deltaY, 32, 48); - // game.debug.text(sprite.body.deltaX(), 232, 32); - // game.debug.text(sprite.body.deltaY(), 232, 48); - - // game.debug.text(sprite.body.left, 32, 32); - // game.debug.text(sprite.body.top, 32, 48); - - // game.debug.spriteCoords(sprite, 32, 320); - -} \ No newline at end of file diff --git a/examples/wip/misc/rect test.js b/examples/wip/misc/rect test.js deleted file mode 100644 index 56f16ff1f..000000000 --- a/examples/wip/misc/rect test.js +++ /dev/null @@ -1,83 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - -} - -var body; -var tile; - -function create() { - - body = { left: 386, top: 89, right: 412, bottom: 127 }; - tile = { x: 416, y: 96, right: 448, bottom: 128 }; - - game.input.keyboard.addKeyCapture([Phaser.Keyboard.LEFT, Phaser.Keyboard.RIGHT, Phaser.Keyboard.UP, Phaser.Keyboard.DOWN]); - -} - -function tileIntersects (body, tile) { - - if (body.width <= 0 || body.height <= 0 || tile.width <= 0 || tile.height <= 0) - { - // return false; - } - - var test1 = body.right < tile.x; - var test2 = body.bottom < tile.y; - var test3 = body.left > tile.right; - var test4 = body.top > tile.bottom; - - result = !(body.right < tile.x || body.bottom < tile.y || body.left > tile.right || body.top > tile.bottom); - - // game.debug.text('intersects: ' + result, 32, 32); - // game.debug.text('test 1: ' + test1, 320, 60); - // game.debug.text('test 2: ' + test2, 320, 80); - // game.debug.text('test 3: ' + test3, 320, 100); - // game.debug.text('test 4: ' + test4, 320, 120); - - return result; - -} - -function update() { - - if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) - { - body.left -= 1; - body.right -= 1; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) - { - body.left += 1; - body.right += 1; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) - { - body.top -= 1; - body.bottom -= 1; - } - - if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) - { - body.top += 1; - body.bottom += 1; - } - -} - -function render() { - - var r = tileIntersects(body, tile); - - game.context.fillStyle = 'rgb(255,0,0)'; - game.context.fillRect(body.left, body.top, body.right-body.left,body.bottom-body.top); - - game.context.fillStyle = 'rgb(0,255,0)'; - game.context.fillRect(tile.x, tile.y, tile.right-tile.x,tile.bottom-tile.y); - -} diff --git a/examples/wip/misc/removeFilter.js b/examples/wip/misc/removeFilter.js deleted file mode 100644 index cf67aba4d..000000000 --- a/examples/wip/misc/removeFilter.js +++ /dev/null @@ -1,51 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -var logo; -var background; -var filter; - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser2.png'); - game.load.script('fire', '../filters/Fire.js'); - -} - -function create() { - - - logo = game.add.sprite(game.world.centerX, game.world.centerY, 'phaser'); - logo.anchor.setTo(0.5, 0.5); - - background = game.add.sprite(0, 0); - background.width = 800; - background.height = 600; - - filter = game.add.filter('Fire', 800, 600); - filter.alpha = 0.0; - - background.filters = [filter]; - - - game.input.onDown.add(removeBackground, this); - -} - -function update() { - - filter.update(); - -} - -function removeBackground() { - - console.log('removeBackground'); - - - // background.filters = null; - background.destroy(); - - // console.log(background.filters); - -} diff --git a/examples/wip/misc/rendertexture1.js b/examples/wip/misc/rendertexture1.js deleted file mode 100644 index 02f14549e..000000000 --- a/examples/wip/misc/rendertexture1.js +++ /dev/null @@ -1,87 +0,0 @@ - -var config = { - - width: "100%", - height: "100%", - renderer: Phaser.WEBGL, - parent: 'phaser-example', - state: { preload: preload, create: create, update: update }, - backgroundColor: '#ff0000' - -}; - -var game = new Phaser.Game(config); - -function preload() { - - game.load.image('spin1', 'assets/sprites/spinObj_01.png'); - game.load.image('spin2', 'assets/sprites/spinObj_02.png'); - game.load.image('spin3', 'assets/sprites/spinObj_03.png'); - game.load.image('spin4', 'assets/sprites/spinObj_04.png'); - game.load.image('spin5', 'assets/sprites/spinObj_05.png'); - game.load.image('spin6', 'assets/sprites/spinObj_06.png'); - game.load.image('spin7', 'assets/sprites/spinObj_07.png'); - game.load.image('spin8', 'assets/sprites/spinObj_08.png'); - -} - -var renderTexture; -var renderTexture2; -var currentTexture; -var outputSprite; -var stuffContainer; -var count = 0; - -function create() { - - // create two render textures.. these dynamic textures will be used to draw the scene into itself - renderTexture = game.add.renderTexture('texture1', game.width, game.height); - renderTexture2 = game.add.renderTexture('textur2e', game.width, game.height); - currentTexture = renderTexture; - - // create a new sprite that uses the render texture we created above - outputSprite = game.add.sprite(game.width/2, game.height/2, currentTexture); - - // align the sprite - outputSprite.anchor.x = 0.5; - outputSprite.anchor.y = 0.5; - - stuffContainer = game.add.group(); - stuffContainer.x = game.width/2; - stuffContainer.y = game.height/2; - - // now create some items and randomly position them in the stuff container - for (var i = 0; i < 20; i++) - { - var item = stuffContainer.create(Math.random() * 400 - 200, Math.random() * 400 - 200, game.rnd.pick(game.cache.getImageKeys())); - item.anchor.setTo(0.5, 0.5); - } - - // used for spinning! - count = 0; - -} - -function update() { - - stuffContainer.addAll('rotation', 0.1); - - count += 0.01; - - // swap the buffers.. - var temp = renderTexture; - renderTexture = renderTexture2; - renderTexture2 = temp; - - // set the new texture - outputSprite.setTexture(renderTexture); - - // twist this up! - stuffContainer.rotation -= 0.01 - outputSprite.scale.x = outputSprite.scale.y = 1 + Math.sin(count) * 0.2; - - // render the stage to the texture - // the true clears the texture before content is rendered - renderTexture2.renderXY(game.stage.display, 0, 0, true); - -} diff --git a/examples/wip/misc/sat1.js b/examples/wip/misc/sat1.js deleted file mode 100644 index 4e2b27778..000000000 --- a/examples/wip/misc/sat1.js +++ /dev/null @@ -1,184 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - -} - -var sprite; -var sprite2; -var sprite3; - -var bmd; - -var b1; -var b2; -var b3; - -var r; - -function create() { - - game.stage.backgroundColor = '#124184'; - - test1(); - - bmd = game.add.bitmapData(800, 600); - var bg = game.add.sprite(0, 0, bmd); - bg.body.moves = false; - - bmd.clear(); - bmd.context.lineWidth = 1; - -} - -function test1() { - - sprite = game.add.sprite(500, 400, 'gameboy', 0); - // sprite = game.add.sprite(0, 0, 'gameboy', 0); - sprite.name = 'red'; - // sprite.pivot.x = 20; - // sprite.pivot.y = 30; - // sprite.anchor.setTo(0.5, 0.5); - - // sprite.body.polygon.translate(20, 20); - - // sprite.body.polygon.rotate(game.math.degToRad(45)); - // sprite.angle = 45; - - // sprite.scale.setTo(2, 2); - // sprite.body.polygon.scale(2, 2); - - sprite.body.bounce.x = 0.8; - - sprite2 = game.add.sprite(0, 400, 'gameboy', 2); - sprite2.name = 'green'; - // sprite2.body = null; - - sprite3 = game.add.sprite(700, 400, 'gameboy', 3); - sprite3.name = 'yellow'; - // sprite3.body = null; - - // b1 = new SAT.Box(new SAT.Vector(sprite.x, sprite.y), sprite.width, sprite.height); - // b2 = new SAT.Box(new SAT.Vector(sprite2.x, sprite2.y), sprite2.width, sprite2.height); - // b3 = new SAT.Box(new SAT.Vector(sprite3.x, sprite3.y), sprite3.width, sprite3.height); - - // r = new SAT.Response(); - - // console.log(b2); - - game.input.onDown.add(launch1, this); - -} - -function launch1() { - - - // console.log(b1); - - sprite.body.velocity.x = -100; - // sprite2.body.velocity.x = -225; - -} - - -function update() { - - // sprite.angle += 0.5; - // sprite.body.polygon.rotate(game.math.degToRad(0.5)); - - /* - b1.pos.x = sprite.x; - b1.pos.y = sprite.y; - - b2.pos.x = sprite2.x; - b2.pos.y = sprite2.y; - - b3.pos.x = sprite3.x; - b3.pos.y = sprite3.y; - - r.clear(); - - if (SAT.testPolygonPolygon(b1.toPolygon(), b2.toPolygon(), r)) - { - console.log(r, b1.pos, b2.pos); - - // b1.pos.sub(r.overlapV); - // sprite.body.velocity.x *= -sprite.body.bounce.x; - - sprite.body.velocity.x = 0; - - sprite.x += Math.abs(r.overlapV.x) + 1; - console.log('sprite moved to', sprite.x); - // sprite.x = b1.pos.x; - // sprite.y = b1.pos.y; - - } - */ - - sprite.body.collide(sprite2.body); - - bmd.clear(); - - if (sprite) - { - renderPolygon(sprite.body.polygon); - // bmd.fillStyle('rgba(255,0,0,0.8'); - // bmd.fillRect(sprite.body.polygon.pos.x, sprite.body.polygon.pos.y, sprite.body.shape.w, sprite.body.shape.h); - } - - if (sprite2) - { - renderPolygon(sprite2.body.polygon); - // bmd.fillStyle('rgba(0,255,0,0.8'); - // bmd.fillRect(sprite2.body.polygon.pos.x, sprite2.body.polygon.pos.y, sprite2.body.shape.w, sprite2.body.shape.h); - } - - if (sprite3) - { - renderPolygon(sprite3.body.polygon); - // bmd.fillStyle('rgba(0,0,255,0.8'); - // bmd.fillRect(sprite3.body.polygon.pos.x, sprite3.body.polygon.pos.y, sprite3.body.shape.w, sprite3.body.shape.h); - } - -} - -function renderPolygon (polygon, color) { - -// console.log(polygon); - // this.start(0, 0, color); - - bmd.context.beginPath(); - bmd.context.moveTo(polygon.pos.x + polygon.points[0].x, polygon.pos.y + polygon.points[0].y); - - for (var i = 1; i < polygon.points.length; i++) - { - bmd.context.lineTo(polygon.pos.x + polygon.points[i].x, polygon.pos.y + polygon.points[i].y); - } - - bmd.context.closePath(); - bmd.context.strokeStyle = 'rgba(255, 255, 255, 1)'; - // bmd.context.strokeStyle = color; - bmd.context.stroke(); - -} - - -function render() { - - if (sprite) - { - // game.debug.bodyInfo(sprite, 16, 24); - game.debug.text(sprite.name + ' x: ' + sprite.x, 16, 500); - game.debug.text(sprite.name + ' world x: ' + sprite.world.x, 16, 520); - } - - if (sprite2) - { - // game.debug.bodyInfo(sprite2, 16, 190); - game.debug.text(sprite2.name + ' x: ' + sprite2.x, 400, 500); - } - -} diff --git a/examples/wip/misc/sci-fly2.js b/examples/wip/misc/sci-fly2.js deleted file mode 100644 index 2e2d502db..000000000 --- a/examples/wip/misc/sci-fly2.js +++ /dev/null @@ -1,93 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.tilemap('level3', 'assets/tilemaps/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/cybernoid.png', 16, 16); - game.load.image('phaser', 'assets/sprites/phaser-ship.png'); - game.load.image('chunk', 'assets/sprites/chunk.png'); - -} - -var map; -var layer; -var cursors; -var sprite; -var emitter; - -function create() { - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = game.add.tilemap('level3'); - - map.addTilesetImage('CybernoidMap3BG_bank.png', 'tiles'); - - layer = map.createLayer(0); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - map.setCollisionByExclusion([7, 32, 35, 36, 47]); - - // layer.debug = true; - - layer.resizeWorld(); - - cursors = game.input.keyboard.createCursorKeys(); - - emitter = game.add.emitter(0, 0, 200); - - emitter.makeParticles('chunk'); - emitter.minRotation = 0; - emitter.maxRotation = 0; - emitter.gravity = 150; - emitter.bounce.setTo(0.5, 0.5); - - sprite = game.add.sprite(200, 70, 'phaser'); - sprite.anchor.setTo(0.5, 0.5); - - game.camera.follow(sprite); - -} - -function particleBurst() { - - emitter.x = sprite.x; - emitter.y = sprite.y; - emitter.start(true, 2000, null, 1); - -} - -function update() { - - game.physics.collide(sprite, layer); - game.physics.collide(emitter, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -150; - particleBurst(); - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 150; - particleBurst(); - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -150; - sprite.scale.x = -1; - particleBurst(); - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 150; - sprite.scale.x = 1; - particleBurst(); - } - -} diff --git a/examples/wip/misc/snake.js b/examples/wip/misc/snake.js deleted file mode 100644 index 65840205c..000000000 --- a/examples/wip/misc/snake.js +++ /dev/null @@ -1,32 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - -} - -var snake; -var bmd; -var cursors; - -function create() { - - bmd = game.add.bitmapData(32, 32); - bmd.context.fillStyle = 'rgb(0, 255, 0)'; - bmd.context.fillRect(0, 0, 32, 32); - - snake = game.add.group(); - - sprite = game.add.sprite(game.world.randomX - 32, game.world.randomY - 64, bmd); - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/misc/snake2.js b/examples/wip/misc/snake2.js deleted file mode 100644 index d7e9b01fb..000000000 --- a/examples/wip/misc/snake2.js +++ /dev/null @@ -1,169 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('snake','assets/games/snake/sprites.png', 32, 32); - game.load.image('ball', 'assets/sprites/pangball.png'); - -} - -var snake; - -var snakeHead; //head of snake sprite -var snakePath = []; //arrary of positions(points) that have to be stored for the path the sections follow -var numSnakeSections = 10; //number of snake body sections -var snakeSpacer = 6; //parameter that sets the spacing between sections -var snakeSpeed = 250; -var snakeLength = 10; - -var fruit; - -var snakeCircles = []; -var node; -var ball; - -function create() { - - game.world.setBounds(0, 0, 800, 600); - - game.stage.backgroundColor = '#0f4e93'; - - cursors = game.input.keyboard.createCursorKeys(); - - snake = game.add.group(); - - snakeHead = snake.create(400, 300, 'snake', 5); - snakeHead.anchor.setTo(0.5, 0.5); - snakeHead.animations.add('chomp', [5, 6], 10, true); - snakeHead.play('chomp'); - snakeHead.body.collideWorldBounds = true; - snakeCircles.push(new Phaser.Circle(snakeHead.x, snakeHead.y, 16)); - - // Init snakeSection array - for (var i = 1; i <= numSnakeSections-1; i++) - { - var snakeSection = snake.create(400, 300, 'snake', 7); - snakeSection.anchor.setTo(0.5, 0.5); - snakeSection.animations.add('walk', [7, 8, 9, 10], 10, true); - snakeSection.play('walk'); - snakeCircles.push(new Phaser.Circle(400, 300, 16)); - - if (i > snakeLength) - { - snakeSection.visible = false; - } - } - - node = new Phaser.Circle(300, 300, 170); - ball = game.add.sprite(node.x, node.y, 'ball'); - ball.anchor.setTo(0.5, 0.5); - - // fruit = game.add.group(); - - // for (var i = 0; i < 20; i++) - // { - // fruit.create(game.world.randomX, game.world.randomY, 'snake', 2); - // } - - // Init snakePath array - for (var i = 0; i <= numSnakeSections * snakeSpacer; i++) - { - snakePath[i] = new Phaser.Point(400, 300); - } - -} - -function newNode() { - - node.x = game.rnd.integerInRange(100, 700); - node.y = game.rnd.integerInRange(100, 500); - ball.x = node.x; - ball.y = node.y; - ball.alpha = 1; - -} - -function update() { - - // game.physics.collide(snakeHead, fruit, eatFruit); - - var enclosed = true; - - for (var i = 0; i <= numSnakeSections - 1; i++) - { - if (Phaser.Circle.intersects(snakeCircles[i], node) === false) - { - enclosed = false; - break; - } - } - - if (enclosed) - { - ball.alpha -= 0.02; - - if (ball.alpha <= 0) - { - newNode(); - } - } - - snakeHead.body.angularVelocity = 0; - - // if (cursors.up.isDown) - // { - snakeHead.body.velocity.copyFrom(game.physics.velocityFromAngle(snakeHead.angle, snakeSpeed)); - - snakeCircles[0].x = snakeHead.x; - snakeCircles[0].y = snakeHead.y; - - var part = snakePath.pop(); - - part.setTo(snakeHead.x, snakeHead.y); - - snakePath.unshift(part); - - for (var i = 1; i <= numSnakeSections - 1; i++) - { - var x = (snakePath[i * snakeSpacer]).x; - var y = (snakePath[i * snakeSpacer]).y; - snake.getAt(i).x = x; - snake.getAt(i).y = y; - snakeCircles[i].x = x; - snakeCircles[i].y = y; - } - // } - - if (cursors.left.isDown) - { - snakeHead.body.angularVelocity = -220; - } - else if (cursors.right.isDown) - { - snakeHead.body.angularVelocity = 220; - } - -} - -function eatFruit(snakeHead, fruit) { - - fruit.kill(); - - snakeLength++; - - snake.getAt(snakeLength).visible = true; - snakeSpeed += 10; - -} - -function render() { - - //game.debug.circle(node); - - for (var i = 0; i <= numSnakeSections - 1; i++) - { - //game.debug.circle(snakeCircles[i], 'rgb(255,0,0)'); - } - - -} \ No newline at end of file diff --git a/examples/wip/misc/sort.js b/examples/wip/misc/sort.js deleted file mode 100644 index fc7f319fe..000000000 --- a/examples/wip/misc/sort.js +++ /dev/null @@ -1,79 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - game.load.tilemap('desert', 'assets/maps/burd.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tiles', 'assets/maps/ground_1x1.png', 32, 32); - game.load.spritesheet('trees', 'assets/maps/walls_1x2.png', 32, 64); - -} - -var map; -var tileset; -var layer; - -var sprite; -var group; -var oldY = 0; -var cursors; - -function create() { - - // Create our tilemap to walk around - map = game.add.tilemap('desert'); - tileset = game.add.tileset('tiles'); - layer = game.add.tilemapLayer(0, 0, 800, 600, tileset, map, 0); - - // This group will hold the main player + all the tree sprites to depth sort against - group = game.add.group(); - - // The player - sprite = group.create(300, 200, 'phaser'); - - // Some trees - for (var i = 0; i < 50; i++) - { - var x = game.math.snapTo(game.world.randomX, 32); - var y = game.math.snapTo(game.world.randomY, 32); - group.create(x, y, 'trees', game.rnd.integerInRange(0, 8)); - } - - // Move it - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - } - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - } - - if (sprite.y !== oldY) - { - // Group.sort() is an expensive operation - // You really want to minimise how often it is called as much as possible. - // So this little check helps at least, but if you can do it even less than this. - group.sort(); - oldY = sprite.y; - } - -} diff --git a/examples/wip/misc/sprite vs sprite.js b/examples/wip/misc/sprite vs sprite.js deleted file mode 100644 index 9213c2092..000000000 --- a/examples/wip/misc/sprite vs sprite.js +++ /dev/null @@ -1,95 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - -} - -var sprite1; -var sprite2; - -var cursors; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - - game.add.sprite(0, 0, 'backdrop'); - - game.stage.backgroundColor = '#2d2d2d'; - - // This will check Sprite vs. Sprite collision - - - - sprite1 = game.add.sprite(50, 250, 'atari'); - sprite1.name = 'atari'; - sprite1.body.immovable = true; - - sprite2 = game.add.sprite(32, 32, 'mushroom'); - sprite2.name = 'mushroom'; - sprite2.body.setCircle(32); - - game.camera.follow(sprite1); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.collide(sprite1, sprite2); - - if (cursors.left.isDown) - { - sprite1.body.x -= 4; - } - else if (cursors.right.isDown) - { - sprite1.body.x += 4; - } - - if (cursors.up.isDown) - { - sprite1.body.y -= 4; - } - else if (cursors.down.isDown) - { - sprite1.body.y += 4; - } - - - /* - sprite1.x = game.input.x; - - if (game.input.y > 300) - { - sprite1.y = game.input.y; - } - else - { - sprite1.y = 300; - } - - if (sprite2.y > 600) - { - sprite2.body.x = 0; - sprite2.body.y = 0; - } - */ - - sprite2.body.velocity.x = 50; - sprite2.body.velocity.y = 100; - -} - -function render() { - - game.debug.physicsBody(sprite1.body); - game.debug.physicsBody(sprite2.body); - -} - diff --git a/examples/wip/misc/struck.js b/examples/wip/misc/struck.js deleted file mode 100644 index 09828d92f..000000000 --- a/examples/wip/misc/struck.js +++ /dev/null @@ -1,125 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level1', 'assets/games/starstruck/level1.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tiles', 'assets/games/starstruck/tiles-1.png', 16, 16); - game.load.spritesheet('dude', 'assets/games/starstruck/dude.png', 32, 48); - game.load.spritesheet('droid', 'assets/games/starstruck/droid.png', 32, 32); - game.load.image('starSmall', 'assets/games/starstruck/star.png'); - game.load.image('starBig', 'assets/games/starstruck/star2.png'); - game.load.image('background', 'assets/games/starstruck/background2.png'); - -} - -var map; -var tileset; -var layer; -var player; -var facing = 'left'; -var jumpTimer = 0; -var cursors; -var jumpButton; -var bg; - -function create() { - - game.stage.backgroundColor = '#000000'; - - bg = game.add.tileSprite(0, 0, 800, 600, 'background'); - bg.fixedToCamera = true; - - map = game.add.tilemap('level1'); - - tileset = game.add.tileset('tiles'); - - tileset.setCollisionRange(0, tileset.total - 1, true, true, true, true); - - tileset.setCollisionRange(12, 16, false, false, false, false); - tileset.setCollisionRange(46, 50, false, false, false, false); - - layer = game.add.tilemapLayer(0, 0, 800, 600, tileset, map, 0); - layer.resizeWorld(); - - player = game.add.sprite(32, 32, 'dude'); - player.body.bounce.y = 0.2; - player.body.collideWorldBounds = true; - player.body.gravity.y = 6; - player.body.setSize(16, 32, 8, 16); - - player.animations.add('left', [0, 1, 2, 3], 10, true); - player.animations.add('turn', [4], 20, true); - player.animations.add('right', [5, 6, 7, 8], 10, true); - - player.angle = 45; - - game.camera.follow(player); - - cursors = game.input.keyboard.createCursorKeys(); - jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); - -} - -function update() { - - game.physics.collide(player, layer); - - player.body.velocity.x = 0; - - if (cursors.left.isDown) - { - player.body.velocity.x = -150; - - if (facing != 'left') - { - player.animations.play('left'); - facing = 'left'; - } - } - else if (cursors.right.isDown) - { - player.body.velocity.x = 150; - - if (facing != 'right') - { - player.animations.play('right'); - facing = 'right'; - } - } - else - { - if (facing != 'idle') - { - player.animations.stop(); - - if (facing == 'left') - { - player.frame = 0; - } - else - { - player.frame = 5; - } - - facing = 'idle'; - } - } - - if (jumpButton.isDown && player.body.touching.down && game.time.now > jumpTimer) - { - player.body.velocity.y = -250; - jumpTimer = game.time.now + 750; - } - - // player.scale.x += 0.001; - // player.scale.y += 0.001; - -} - -function render () { - - game.debug.cameraInfo(game.camera, 32, 32); - game.debug.spriteBody(player); - -} diff --git a/examples/wip/misc/supermario.js b/examples/wip/misc/supermario.js deleted file mode 100644 index 441ba8642..000000000 --- a/examples/wip/misc/supermario.js +++ /dev/null @@ -1,81 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update}); - -function preload() { - - game.load.tilemap('background', 'assets/maps/smb_bg.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tilesBackground', 'assets/maps/smb_bg.png',16,16); - - game.load.tilemap('level1', 'assets/maps/smb_level1.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tilesLevel1', 'assets/maps/smb_tiles.png',16,16); - -} - -var mapBg; -var tilesetBg; -var layerBg; -var mapLevel1; -var tilesetLevel1; -var layerLevel1; -var cursors; - -function create() { - - game.stage.backgroundColor = '#787878'; - - mapBg = game.add.tilemap('background'); - - tilesetBg = game.add.tileset('tilesBackground'); - - - layerBg = game.add.tilemapLayer(0, 0, mapBg.layers[0].width*tilesetBg.tileWidth, 600, tilesetBg, mapBg, 0); - - layerBg.fixedToCamera=false; - - layerBg.resizeWorld(); - - - mapLevel1 = game.add.tilemap('level1'); - - tilesetLevel1 = game.add.tileset('tilesLevel1'); - - - layerLevel1 = game.add.tilemapLayer(0, 0, mapLevel1.layers[0].width*tilesetLevel1.tileWidth, 600, tilesetLevel1, mapLevel1, 0); - - layerLevel1.fixedToCamera=false; - - cursors=game.input.keyboard.createCursorKeys(); - - balls = game.add.emitter(300, 50, 500); - balls.bounce = 0.5; - balls.makeParticles('balls', [0,1,2,3,4,5], 500, 1); - balls.minParticleSpeed.setTo(-150, 150); - balls.maxParticleSpeed.setTo(100, 100); - balls.gravity = 8; - balls.start(false, 5000, 50); - - game.add.tween(balls).to({ x: 4000 }, 7500, Phaser.Easing.Sinusoidal.InOut, true, 0, 1000, true); - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 18; - } - else if (cursors.right.isDown) - { - game.camera.x += 18; - } - - if (cursors.up.isDown) - { - game.camera.y -= 18; - } - else if (cursors.down.isDown) - { - game.camera.y += 18; - } - -} diff --git a/examples/wip/misc/supermario2.js b/examples/wip/misc/supermario2.js deleted file mode 100644 index fdb48964a..000000000 --- a/examples/wip/misc/supermario2.js +++ /dev/null @@ -1,95 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update}); - -function preload() { - - game.load.tilemap('background', 'assets/maps/smb_bg.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tilesBackground', 'assets/maps/smb_bg.png',16,16); - - game.load.tilemap('level1', 'assets/maps/smb_level1.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tilesLevel1', 'assets/maps/smb_tiles.png',16,16); - - game.load.spritesheet('balls', 'assets/sprites/balls.png', 17, 17); - -} - -var mapBg; -var tilesetBg; -var layerBg; -var mapLevel1; -var tilesetLevel1; -var layerLevel1; -var cursors; -var balls; - -function create() { - - game.stage.backgroundColor = '#787878'; - - mapBg = game.add.tilemap('background'); - - tilesetBg = game.add.tileset('tilesBackground'); - - - layerBg = game.add.tilemapLayer(0, 0, mapBg.layers[0].width*tilesetBg.tileWidth, 600, tilesetBg, mapBg, 0); - - layerBg.fixedToCamera=false; - - layerBg.resizeWorld(); - - - mapLevel1 = game.add.tilemap('level1'); - - tilesetLevel1 = game.add.tileset('tilesLevel1'); - - tilesetLevel1.setCollisionRange(9,11,true,true,true,true); - tilesetLevel1.setCollisionRange(14,19,true,true,true,true); - tilesetLevel1.setCollisionRange(22,24,true,true,true,true); - tilesetLevel1.setCollisionRange(37,38,true,true,true,true); - - tilesetLevel1.setCollision(32,true,true,true,true); - - - layerLevel1 = game.add.tilemapLayer(0, 0, mapLevel1.layers[0].width*tilesetLevel1.tileWidth, 600, tilesetLevel1, mapLevel1, 0); - - layerLevel1.fixedToCamera=false; - - layerLevel1.resizeWorld(); - - cursors=game.input.keyboard.createCursorKeys(); - - balls = game.add.emitter(300, 50, 500); - balls.bounce = 0.5; - balls.makeParticles('balls', [0,1,2,3,4,5], 500, 1); - balls.minParticleSpeed.setTo(-150, 150); - balls.maxParticleSpeed.setTo(100, 100); - balls.gravity = 8; - balls.start(false, 5000, 50); - - game.add.tween(balls).to({ x: 4000 }, 7500, Phaser.Easing.Sinusoidal.InOut, true, 0, 1000, true); - -} - -function update() { - - game.physics.collide(balls,layerLevel1); - - if (cursors.left.isDown) - { - game.camera.x -= 18; - } - else if (cursors.right.isDown) - { - game.camera.x += 18; - } - - if (cursors.up.isDown) - { - game.camera.y -= 18; - } - else if (cursors.down.isDown) - { - game.camera.y += 18; - } - -} diff --git a/examples/wip/misc/swap.js b/examples/wip/misc/swap.js deleted file mode 100644 index 294b9a60c..000000000 --- a/examples/wip/misc/swap.js +++ /dev/null @@ -1,89 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - game.load.spritesheet('veggies', 'assets/sprites/fruitnveg32wh37.png', 32, 32); - -} - -var group; -var start = false; -var swapCount = 0; -var time = 0; -var test = 0; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - group = game.add.group(); - - for (var i = 0; i < 500; i++) - { - var c = group.create(game.world.randomX, game.world.randomY, 'veggies', game.rnd.integerInRange(0, 36)); - c.name = 'veg' + i; - } - - test = group.length; - - game.input.onUp.add(toggleSwap, this); - -} - -function toggleSwap () { - - if (start) - { - start = false; - } - else - { - start = true; - } - -} - -function update() { - - if (start && game.time.now > time) - { - var a = group.getRandom(); - var b = group.getRandom(); - - if (a.name !== b.name) - { - // console.log('************************ NEW ROUND *********************'); - // group.dump(true); - // console.log('Group Size: ' + group.length); - group.swap(a, b); - swapCount++; - - if (group.length !== test) - { - start = false; - console.log('************************ SHIT *********************'); - group.dump(true); - console.log('************************ SHIT *********************'); - } - - if (group.validate() == false) - { - start = false; - console.log('************************ VALIDATE FAIL *********************'); - group.dump(true); - console.log('************************ VALIDATE FAIL *********************'); - } - - } - - // time = game.time.now + 50; - } - -} - -function render() { - - game.debug.text('Swap: ' + swapCount, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/misc/text on top.js b/examples/wip/misc/text on top.js deleted file mode 100644 index b646b373b..000000000 --- a/examples/wip/misc/text on top.js +++ /dev/null @@ -1,61 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render : render }); - -function preload() { - - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -var cursors; -var group; -var text; -var timer; - -function create() { - - game.stage.backgroundColor = '#007236'; - - for (var i = 0; i < 200; i++) - { - game.add.sprite(game.world.randomX, game.world.randomY, 'mushroom'); - } - - text = game.add.text(0, 0, "Text Above Sprites", { font: "64px Arial", fill: "#00bff3", align: "center" }); - - timer = new Phaser.Timer(game); - timer.add(1000); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - timer.update(); - - if (cursors.up.isDown) - { - text.y -= 4; - } - else if (cursors.down.isDown) - { - text.y += 4; - } - - if (cursors.left.isDown) - { - text.x -= 4; - } - else if (cursors.right.isDown) - { - text.x += 4; - } - -} - -function render() { - - // game.debug.cameraInfo(game.camera, 32, 32); - -} diff --git a/examples/wip/misc/tilemap poly.js b/examples/wip/misc/tilemap poly.js deleted file mode 100644 index 834ffee81..000000000 --- a/examples/wip/misc/tilemap poly.js +++ /dev/null @@ -1,105 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser1.png'); - game.load.spritesheet('arrows', 'assets/sprites/arrows.png', 23, 31); - -} - -var arrowStart; -var arrowEnd; -var sprite; - -function create() { - - game.stage.backgroundColor = '#2384e7'; - - // game.physics.setBoundsToWorld(true, true, false, false); - - // arrowStart = game.add.sprite(100, 100, 'arrows', 0); - // arrowEnd = game.add.sprite(400, 100, 'arrows', 1); - - // sprite = game.add.sprite(100, 164, 'phaser'); - sprite = game.add.sprite(300, 364, 'phaser'); - // sprite.anchor.setTo(0.5, 0.5); - sprite.inputEnabled = true; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(1, 1); - sprite.alpha = 0.2; - - // sprite.body.allowRotation = true; - // sprite.body.polygon.translate(100, 0); - - - // sprite.body.setPolygon([new SAT.Vector(0,0), new SAT.Vector(60, 0), new SAT.Vector(100, 40), new SAT.Vector(60, 80), new SAT.Vector(0, 80)], -50, -40); - - sprite.body.setPolygon([new SAT.Vector(0,50), new SAT.Vector(100, 50), new SAT.Vector(100, 0), new SAT.Vector(150, 0), new SAT.Vector(150, 150), new SAT.Vector(100, 150), new SAT.Vector(100, 100), new SAT.Vector(0, 100), new SAT.Vector(0, 50)], -100, -100); - - - // sprite.body.setCircle(50); - // sprite.body.offset.setTo(50, 50); - - // console.log(sprite.body.x, sprite.body.y, sprite.body.shape.radius); - - sprite.events.onInputDown.add(move, this); - - // sprite.body.polygons.rotate(0.4); - // sprite.rotation = 0.4; - - // console.log(sprite.body.polygons); - -} - -function move() { - - console.log('move'); - - sprite.body.velocity.x = 200; - sprite.body.velocity.y = -200; - // sprite.body.angularVelocity = 2; - - // sprite.rotation = 0.4; - - // console.log(sprite.body.polygon.points); - - // to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { - - // game.add.tween(sprite).to( { angle: 359 }, 8000, Phaser.Easing.Linear.None, true, 0, 1000, false); - - // sprite.scale.setTo(2, 2); - - if (sprite.x === 100) - { - // Here you'll notice we are using a relative value for the tween. - // You can specify a number as a string with either + or - at the start of it. - // When the tween starts it will take the sprites current X value and add +300 to it. - - // game.add.tween(sprite).to( { x: '+300' }, 2000, Phaser.Easing.Linear.None, true); - } - else if (sprite.x === 400) - { - // game.add.tween(sprite).to( { x: '-300' }, 2000, Phaser.Easing.Linear.None, true); - } - -} - -function render() { - - if (sprite.x === 100 || sprite.x === 400) - { - // game.debug.text('Click sprite to tween', 32, 32); - } - - // game.debug.text('x: ' + arrowStart.x, arrowStart.x, arrowStart.y - 4); - // game.debug.text('x: ' + arrowEnd.x, arrowEnd.x, arrowEnd.y - 4); - - game.debug.text('sprite.x: ' + sprite.x + ' deltaX: ' + sprite.deltaX, 32, 32); - game.debug.text('sprite.y: ' + sprite.y + ' deltaY: ' + sprite.deltaY, 32, 48); - - game.debug.physicsBody(sprite.body); - - game.debug.point(sprite.center); - -} diff --git a/examples/wip/misc/tilemap.js b/examples/wip/misc/tilemap.js deleted file mode 100644 index 7db20648d..000000000 --- a/examples/wip/misc/tilemap.js +++ /dev/null @@ -1,217 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - // game.load.tilemap('map', 'assets/maps/super_mario.json', null, Phaser.Tilemap.TILED_JSON); - // game.load.tileset('tiles', 'assets/maps/super_mario.png', 16, 16); - - game.load.tilemap('map', 'assets/tilemaps/maps/features_test.json', null, Phaser.Tilemap.TILED_JSON); - - // game.load.image('ground', 'assets/maps/ground_1x1.png'); - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('walls_1x2', 'assets/tilemaps/tiles/walls_1x2.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - - - // game.load.tileset('tiles', 'assets/maps/ground_1x1.png', 32, 32); - // game.load.image('phaser', 'assets/sprites/phaser-ship.png'); - // game.load.image('phaser', 'assets/sprites/mushroom2.png'); - game.load.image('phaser', 'assets/sprites/wabbit.png'); - // game.load.image('phaser', 'assets/sprites/arrow.png'); - game.load.spritesheet('coin', 'assets/sprites/coin.png', 32, 32); - // game.load.image('phaser', 'assets/sprites/darkwing_crazy.png'); - -} - -var cursors; -var map; -var coins; - -var layer; -var layer2; -var layer3; - -var sprite; - -function create() { - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('walls_1x2'); - map.addTilesetImage('tiles2'); - - map.setCollisionBetween(1, 12); - - // mario tiles - // map.setCollisionByIndex(15); - // map.setCollisionByIndex(40); - // map.setCollisionByIndexRange(14, 16); - // map.setCollisionByIndexRange(20, 25); - // map.setCollisionByIndexRange(27, 29); - - // layer3 = map.createLayer('Tile Layer 3'); - // layer3.scrollFactorX = 0.5; - - // layer2 = map.createLayer('Tile Layer 2'); - // layer2.alpha = 0.5; - - layer = map.createLayer('Tile Layer 1'); - - layer.debug = true; - - layer.resizeWorld(); - - //coins = - map.createFromObjects('Object Layer 1', 34, 'coin', 0); - - // layer2 = game.add.tilemapLayer(0, 0, 400, 600, null, map, 0); - // layer.cameraOffset.x = 400; - // layer.alpha = 0.5; - - - sprite = game.add.sprite(260, 100, 'phaser'); - // sprite.anchor.setTo(0.5, 0.5); - - // This adjusts the collision body size. - // 100x50 is the new width/height. - // 50, 25 is the X and Y offset of the newly sized box. - // In this case the box is 50px in and 25px down. - // sprite.body.setSize(16, 16, 8, 8); - - // We'll set a lower max angular velocity here to keep it from going totally nuts - sprite.body.maxAngular = 500; - - // Apply a drag otherwise the sprite will just spin and never slow down - sprite.body.angularDrag = 50; - - // sprite.body.drag.x = 50; - // sprite.body.drag.y = 20; - - // sprite.body.velocity.x = 50; - - sprite.body.bounce.x = 0.8; - sprite.body.bounce.y = 0.8; - - // sprite.angle = 35; - - // game.camera.follow(sprite); - - // game.input.onDown.add(getIt, this); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function getIt() { - - // console.log('cam', game.camera.bounds); - // console.log('w', game.world.bounds); - // console.log(layer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true, true)); - -} - -function update() { - -/* - if (cursors.left.isDown) - { - game.camera.x -= 1; - } - else if (cursors.right.isDown) - { - game.camera.x += 1; - } - - if (cursors.up.isDown) - { - layer.scrollY -= 4; - } - else if (cursors.down.isDown) - { - layer.scrollY += 4; - } -*/ - game.physics.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - // sprite.body.acceleration.x = 0; - // sprite.body.angularAcceleration = 0; - - /* - if (cursors.left.isDown) - { - // sprite.body.acceleration.x = -200; - sprite.body.angularVelocity = -300; - // sprite.body.angularAcceleration -= 200; - } - else if (cursors.right.isDown) - { - // sprite.body.acceleration.x = 200; - sprite.body.angularVelocity = 300; - // sprite.body.angularAcceleration += 200; - } - - if (cursors.up.isDown) - { - game.physics.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - else - { - // game.physics.velocityFromAngle(sprite.angle, sprite.body.velocity, sprite.body.velocity); - } - */ - - - - - /* - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - sprite.angle = sprite.angle + 1; - */ - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -100; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 100; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -100; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 100; - } - - -} - -function render() { - - // game.debug.spriteBody(sprite); - // game.debug.spriteBounds(sprite); - game.debug.physicsBody(sprite.body); - - // game.debug.text(sprite.deltaX, 32, 32); - // game.debug.text(sprite.deltaY, 32, 48); - // game.debug.text(sprite.body.deltaX(), 232, 32); - // game.debug.text(sprite.body.deltaY(), 232, 48); - - // game.debug.text(sprite.body.left, 32, 32); - // game.debug.text(sprite.body.right, 32, 48); - - game.debug.spriteCoords(sprite, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/misc/timer simple.js b/examples/wip/misc/timer simple.js deleted file mode 100644 index d37d54c78..000000000 --- a/examples/wip/misc/timer simple.js +++ /dev/null @@ -1,53 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('ball', 'assets/sprites/pangball.png'); - -} - -var t; - -function create() { - - game.stage.backgroundColor = '#6688ee'; - - t = game.time.create(false); - - t.repeat(Phaser.Timer.SECOND * 2, 10, createBall, this); - t.repeat(Phaser.Timer.SECOND * 3, 10, createBall, this); - - t.start(); - - game.input.onDown.add(killThem, this); - -} - -function createBall() { - - // A bouncey ball sprite just to visually see what's going on. - var ball = game.add.sprite(game.world.randomX, 0, 'ball'); - - ball.body.gravity.y = 200; - ball.body.bounce.y = 0.5; - ball.body.collideWorldBounds = true; - -console.log('nuked'); - game.time.removeAll(); - // t.removeAll(); - - -} - -function killThem() { - - -} - -function render() { - - game.debug.text("Time until event: " + t.duration.toFixed(0), 32, 32); - game.debug.text("Next tick: " + t.next.toFixed(0), 32, 64); - -} diff --git a/examples/wip/misc/tween-limit.js b/examples/wip/misc/tween-limit.js deleted file mode 100644 index 5a46976f7..000000000 --- a/examples/wip/misc/tween-limit.js +++ /dev/null @@ -1,55 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser1.png'); - game.load.spritesheet('arrows', 'assets/sprites/arrows.png', 23, 31); - -} - -var arrowStart; -var arrowEnd; -var sprite; - -function create() { - - game.stage.backgroundColor = '#2384e7'; - - arrowStart = game.add.sprite(100, 100, 'arrows', 0); - - arrowEnd = game.add.sprite(400, 100, 'arrows', 1); - - sprite = game.add.sprite(100, 164, 'phaser'); - sprite.inputEnabled = true; - - sprite.events.onInputDown.add(move, this); - -} - -function move() { - - var tween = game.add.tween(sprite).to( { x: '+500' }, 3000, Phaser.Easing.Linear.None, true); - - tween.onComplete.add(over, this); - -} - -function over() { - console.log('done'); - sprite.alpha = 0.5; -} - -function update() { - - if (sprite.x > 200) - { - sprite.x = 200; - } - -} - -function render() { - - -} diff --git a/examples/wip/misc/tween-relative.js b/examples/wip/misc/tween-relative.js deleted file mode 100644 index 4a1aace84..000000000 --- a/examples/wip/misc/tween-relative.js +++ /dev/null @@ -1,102 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, render: render }); - -function preload() { - - game.load.image('phaser', 'assets/sprites/phaser1.png'); - game.load.spritesheet('arrows', 'assets/sprites/arrows.png', 23, 31); - -} - -var arrowStart; -var arrowEnd; -var sprite; - -function create() { - - game.stage.backgroundColor = '#2384e7'; - - // game.physics.setBoundsToWorld(true, true, false, false); - - // arrowStart = game.add.sprite(100, 100, 'arrows', 0); - // arrowEnd = game.add.sprite(400, 100, 'arrows', 1); - - // sprite = game.add.sprite(100, 164, 'phaser'); - sprite = game.add.sprite(300, 364, 'phaser'); - sprite.anchor.setTo(0.5, 0.5); - sprite.inputEnabled = true; - sprite.body.collideWorldBounds = true; - sprite.body.bounce.setTo(1, 1); - - // sprite.body.allowRotation = true; - // sprite.body.polygon.translate(100, 0); - - - sprite.body.setPolygon([new SAT.Vector(0,0), new SAT.Vector(60, 0), new SAT.Vector(100, 40), new SAT.Vector(60, 80), new SAT.Vector(0, 80)], -50, -40); - - - // sprite.body.setCircle(50); - // sprite.body.offset.setTo(50, 50); - - // console.log(sprite.body.x, sprite.body.y, sprite.body.shape.radius); - - sprite.events.onInputDown.add(move, this); - - // sprite.body.polygons.rotate(0.4); - // sprite.rotation = 0.4; - - // console.log(sprite.body.polygons); - -} - -function move() { - - console.log('move'); - - sprite.body.velocity.x = 200; - sprite.body.velocity.y = -200; - // sprite.body.angularVelocity = 2; - - // sprite.rotation = 0.4; - - // console.log(sprite.body.polygon.points); - - // to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) { - - game.add.tween(sprite).to( { angle: 359 }, 4000, Phaser.Easing.Linear.None, true, 0, 1000, false); - - // sprite.scale.setTo(2, 2); - - if (sprite.x === 100) - { - // Here you'll notice we are using a relative value for the tween. - // You can specify a number as a string with either + or - at the start of it. - // When the tween starts it will take the sprites current X value and add +300 to it. - - // game.add.tween(sprite).to( { x: '+300' }, 2000, Phaser.Easing.Linear.None, true); - } - else if (sprite.x === 400) - { - // game.add.tween(sprite).to( { x: '-300' }, 2000, Phaser.Easing.Linear.None, true); - } - -} - -function render() { - - if (sprite.x === 100 || sprite.x === 400) - { - // game.debug.text('Click sprite to tween', 32, 32); - } - - // game.debug.text('x: ' + arrowStart.x, arrowStart.x, arrowStart.y - 4); - // game.debug.text('x: ' + arrowEnd.x, arrowEnd.x, arrowEnd.y - 4); - - game.debug.text('sprite.x: ' + sprite.x + ' deltaX: ' + sprite.deltaX, 32, 32); - game.debug.text('sprite.y: ' + sprite.y + ' deltaY: ' + sprite.deltaY, 32, 48); - - game.debug.physicsBody(sprite.body); - - game.debug.point(sprite.center); - -} diff --git a/examples/wip/misc/wabbits.js b/examples/wip/misc/wabbits.js deleted file mode 100644 index c7ba19325..000000000 --- a/examples/wip/misc/wabbits.js +++ /dev/null @@ -1,163 +0,0 @@ -// mods by Patrick OReilly -// twitter: @pato_reilly - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('analog', 'assets/tests/fusia.png'); - game.load.image('arrow', 'assets/sprites/longarrow2.png'); - game.load.image('ball', 'assets/sprites/pangball.png'); - game.load.image('hill', 'assets/pics/atari_fujilogo.png'); - game.load.image('block', 'assets/sprites/block.png'); - game.load.image('wabbit', 'assets/sprites/wabbit.png'); - -} - -var arrow; -var ball; -var catchFlag = false; -var wabbits; -var wab; -var launchVelocity = 0; -var shotCount = 0; -var wabbitCount = 0; - -function create() { - - // set global gravity - game.physics.gravity.y = 200; - - game.stage.backgroundColor = '#0072bc'; - - var graphics = game.add.graphics(0, 0); - graphics.beginFill(0x049e0c); - graphics.drawRect(195, 450, 10, 150); - - wabbits = game.add.group(); - - for (var i = 0; i < 5; i++) - { - wab = wabbits.create(game.rnd.integerInRange(575, 650), game.rnd.integerInRange(150, 260), 'wabbit'); - wab.name = 'wab' + i; - wab.body.collideWorldBounds = true; - wab.body.mass = 0.1; - wab.body.linearDamping = 0.2; - } - - hill = game.add.sprite(450, 400, 'hill'); - hill.body.collideWorldBounds = true; - hill.body.mass = 10; - hill.body.immovable = true; - - block = game.add.sprite(575, 300, 'block'); - block.body.collideWorldBounds = true; - block.body.mass = 5; - block.body.linearDamping = 0.4; - - analog = game.add.sprite(200, 450, 'analog'); - analog.body.allowGravity = false; - analog.width = 8; - analog.rotation = 220; - analog.alpha = 0; - analog.anchor.setTo(0.5, 0.0); - - arrow = game.add.sprite(200, 450, 'arrow'); - arrow.anchor.setTo(0.1, 0.5); - arrow.body.allowGravity = false; - arrow.alpha = 0; - - ball = game.add.sprite(100, 400, 'ball'); - ball.anchor.setTo(0.5, 0.5); - ball.inputEnabled = true; - ball.body.collideWorldBounds = true; - ball.body.bounce.setTo(0.9, 0.9); - ball.body.linearDamping = 0.2; - ball.body.immovable = true; - - // Enable input. - ball.input.start(0, true); - ball.events.onInputDown.add(set); - ball.events.onInputUp.add(launch); - -} - -function set(ball, pointer) { - - ball.body.velocity.setTo(0, 0); - ball.body.allowGravity = false; - catchFlag = true; - -} - -function launch() { - - catchFlag = false; - shotCount++; - arrow.alpha = 0; - analog.alpha = 0; - Xvector = (arrow.x - ball.x) * 4.1; - Yvector = (arrow.y - ball.y) * 4.1; - ball.body.allowGravity = true; - ball.body.velocity.setTo(Xvector,Yvector); - -} - -function update() { - - arrow.rotation = game.physics.angleBetween(arrow, ball); - - if (catchFlag == true) - { - // Track the ball sprite to the mouse - ball.x = game.input.activePointer.worldX; - ball.y = game.input.activePointer.worldY; - - arrow.alpha = 1; - analog.alpha = 0.5; - analog.rotation = arrow.rotation - 3.14 / 2; - analog.height = game.physics.distanceToPointer(arrow); - launchVelocity = analog.height; - } - - game.physics.collide(ball, wabbits); - game.physics.collide(wabbits, wabbits); - game.physics.collide(wabbits, hill); - game.physics.collide(ball, hill); - game.physics.collide(block, hill); - game.physics.collide(block, ball); - game.physics.collide(block, wabbits); - - // check wabbits - var wabs = 0; - - for (var i = 0; i < 5; i++) - { - thisWab = wabbits.getAt(i); - - if (thisWab.x > 770 && thisWab.y > 400) - { - thisWab.alive = false; - wabs++; - } - } - - wabbitCount = 5 - wabs; - - // console.log(ball.body.y, ball.body.motionVelocity.y); - -} - -function render() { - - // game.debug.spriteCollision(ball, 32, 32); - - // var graphics = game.add.graphics(0, 0); - // game.context.fillStyle = 'rgba(0,0,255,0.5)'; - // game.context.fillRect(770, 400, 30, 200); - // game.debug.text("Drag the ball to launch", 32, 32); - // game.debug.text("Try to get all 5 wabbits in the blue area with the least number of shots", 32, 64); - // game.debug.text("Shot Count: " + shotCount, 32, 96); - // game.debug.text("Wabbits Left: " + wabbitCount, 32, 128); - -} diff --git a/examples/wip/misc/wip1.js b/examples/wip/misc/wip1.js deleted file mode 100644 index 28c2593fe..000000000 --- a/examples/wip/misc/wip1.js +++ /dev/null @@ -1,158 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level3', 'assets/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tiles', 'assets/maps/cybernoid.png', 16, 16); - -} - -var map; -var tileset; -var layer; -var cursors; -var sprite2; -var overlap; - -function create() { - - game.stage.backgroundColor = '#3d3d3d'; - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = new Phaser.Tilemap(game, 'level3'); - - // A Tileset is a single image containing a strip of tiles. Each tile is broken down into its own Phaser.Tile object on import. - // You can set properties on the Tile objects, such as collision, n-way movement and meta data. - // A Tilemap uses a Tileset to render. The indexes in the map corresponding to the Tileset indexes. - // This way multiple levels can share the same single Tileset without requiring one each. - tileset = game.cache.getTileset('tiles'); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - tileset.setCollisionRange(0, tileset.total - 1, true, true, true, true); - - // And this turns off collision on the only tile we don't want collision on :) - tileset.setCollision(6, false, false, false, false); - - // A TilemapLayer consists of an x,y coordinate (position), a width and height, a Tileset and a Tilemap which it uses for map data. - // The x/y coordinates are in World space and you can place the tilemap layer anywhere in the world. - // The width/height is the rendered size of the layer in pixels, not the size of the map data itself. - - // This one gives tileset as a string, the other an object - // layer = new Phaser.TilemapLayer(game, 0, 0, 640, 400, 'tiles', map, 0); - layer = new Phaser.TilemapLayer(game, 0, 0, 640, 400, tileset, map, 0); - - // To set tiles for collision you need to modify the Tileset, which is a property of the layer - - // Task now - // - // 1) Get tiles that will collide with sprites new position (hullX and hullY) - // 2) Separate x/y - - - // Collision is based on the layer.x/y value - - // layer.sprite.anchor.setTo(0.5, 0.5); - - game.world.add(layer.sprite); - - // This is a bit nuts, ought to find a way to automate it, but it looks cool :) - map.debugMap = [ '#000000', - '#e40058', '#e40058', '#e40058', '#80d010', '#bcbcbc', '#e40058', '#000000', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc', '#e40058', '#e40058', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#80d010', '#80d010', '#80d010', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#80d010', '#0070ec', - '#0070ec', '#24188c', '#24188c', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#80d010', '#80d010', '#80d010', '#e40058', - '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#80d010', '#bcbcbc', '#80d010', '#000000', '#80d010', - '#80d010', '#80d010', '#bcbcbc', '#e40058', '#80d010', '#80d010', '#e40058', '#e40058', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc' - ]; - - // map.dump(); - - // layer.sprite.scale.setTo(2, 2); - - // Works a treat :) - // game.add.sprite(320, 0, layer.texture, layer.frame); - // game.add.sprite(0, 200, layer.texture, layer.frame); - // game.add.sprite(320, 200, layer.texture, layer.frame); - - // game.world.setBounds(0, 0, 2000, 2000); - // game.camera.x = 400; - - cursors = game.input.keyboard.createCursorKeys(); -} - -function update() { - - // layer.sprite.angle += 0.5; - - if (cursors.up.isDown) - { - layer.y -= 4; - } - else if (cursors.down.isDown) - { - layer.y += 4; - } - - if (cursors.left.isDown) - { - layer.x -= 4; - } - else if (cursors.right.isDown) - { - layer.x += 4; - } - - // getTiles: function (x, y, width, height, collides, layer) { - overlap = layer.getTiles(layer.x, layer.y, 128, 128); - -} - -function render() { - - layer.render(); - - game.context.save(); - game.context.setTransform(1, 0, 0, 1, 0, 0); - game.context.fillStyle = 'rgba(255, 0, 0, 0.5)'; - - if (overlap.length > 1) - { - var x = 0; - var y = 0; - - for (var i = 1; i < overlap.length; i++) - { - game.context.drawImage( - overlap[i].tile.tileset.image, - overlap[i].tile.x, - overlap[i].tile.y, - overlap[i].tile.width, - overlap[i].tile.height, - 0 + (x * overlap[i].tile.width), - 420 + (y * overlap[i].tile.height), - overlap[i].tile.width, - overlap[i].tile.height - ); - - if (overlap[i].tile.collideNone == false) - { - game.context.fillRect(0 + (x * overlap[i].tile.width), 420 + (y * overlap[i].tile.height), overlap[i].tile.width, overlap[i].tile.height); - } - - x++; - - if (x == overlap[0].tw) - { - x = 0; - y++; - } - } - } - - game.context.restore(); - -} diff --git a/examples/wip/misc/wip2.js b/examples/wip/misc/wip2.js deleted file mode 100644 index dc1ec2ead..000000000 --- a/examples/wip/misc/wip2.js +++ /dev/null @@ -1,189 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level3', 'assets/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tiles', 'assets/maps/cybernoid.png', 16, 16); - // game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - game.load.image('phaser', 'assets/sprites/space-baddie.png'); - -} - -var map; -var tileset; -var layer; -var cursors; -var overlap; -var sprite; - -function create() { - - game.stage.backgroundColor = '#3d3d3d'; - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = new Phaser.Tilemap(game, 'level3'); - - // A Tileset is a single image containing a strip of tiles. Each tile is broken down into its own Phaser.Tile object on import. - // You can set properties on the Tile objects, such as collision, n-way movement and meta data. - // A Tilemap uses a Tileset to render. The indexes in the map corresponding to the Tileset indexes. - // This way multiple levels can share the same single Tileset without requiring one each. - tileset = game.cache.getTileset('tiles'); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - tileset.setCollisionRange(0, tileset.total - 1, true, true, true, true); - - // And this turns off collision on the only tile we don't want collision on :) - tileset.setCollision(6, false, false, false, false); - tileset.setCollision(34, false, false, false, false); - tileset.setCollision(35, false, false, false, false); - - // A TilemapLayer consists of an x,y coordinate (position), a width and height, a Tileset and a Tilemap which it uses for map data. - // The x/y coordinates are in World space and you can place the tilemap layer anywhere in the world. - // The width/height is the rendered size of the layer in pixels, not the size of the map data itself. - - // This one gives tileset as a string, the other an object - // layer = new Phaser.TilemapLayer(game, 0, 0, 640, 400, 'tiles', map, 0); - layer = new Phaser.TilemapLayer(game, 0, 0, 800, 400, tileset, map, 0); - - // To set tiles for collision you need to modify the Tileset, which is a property of the layer - - // Task now - // - // 1) Get tiles that will collide with sprites new position (hullX and hullY) - // 2) Separate x/y - - - // Collision is based on the layer.x/y value - - // layer.sprite.anchor.setTo(0.5, 0.5); - - game.world.add(layer.sprite); - - // This is a bit nuts, ought to find a way to automate it, but it looks cool :) - map.debugMap = [ '#000000', - '#e40058', '#e40058', '#e40058', '#80d010', '#bcbcbc', '#e40058', '#000000', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc', '#e40058', '#e40058', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#80d010', '#80d010', '#80d010', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#80d010', '#0070ec', - '#0070ec', '#24188c', '#24188c', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#80d010', '#80d010', '#80d010', '#e40058', - '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#80d010', '#bcbcbc', '#80d010', '#000000', '#80d010', - '#80d010', '#80d010', '#bcbcbc', '#e40058', '#80d010', '#80d010', '#e40058', '#e40058', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc' - ]; - - // map.dump(); - - // layer.sprite.scale.setTo(2, 2); - - // Works a treat :) - // game.add.sprite(320, 0, layer.texture, layer.frame); - // game.add.sprite(0, 200, layer.texture, layer.frame); - // game.add.sprite(320, 200, layer.texture, layer.frame); - - // game.world.setBounds(0, 0, 2000, 2000); - // game.camera.x = 400; - - sprite = game.add.sprite(200, 80, 'phaser'); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - sprite.body.velocity.setTo(0, 0); - - // layer.sprite.angle += 0.5; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -100; - // layer.y -= 4; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 100; - // layer.y += 4; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -100; - // layer.x -= 4; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 100; - // layer.x += 4; - } - - // getTiles: function (x, y, width, height, collides, layer) { - overlap = layer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true); - - if (overlap.length > 1) - { - // console.log('%c ', 'background: #000000') - for (var i = 1; i < overlap.length; i++) - { - game.physics.separateTile(sprite.body, overlap[i]); - } - } - -} - -function render() { - - layer.render(); - - game.debug.spriteInfo(sprite, 32, 450); - // game.debug.cameraInfo(game.camera, 32, 32); - - /* - game.context.save(); - game.context.setTransform(1, 0, 0, 1, 0, 0); - - - game.context.fillStyle = 'rgba(255, 0, 0, 0.5)'; - - if (overlap.length > 1) - { - var x = 0; - var y = 0; - - for (var i = 1; i < overlap.length; i++) - { - game.context.drawImage( - overlap[i].tile.tileset.image, - overlap[i].tile.x, - overlap[i].tile.y, - overlap[i].tile.width, - overlap[i].tile.height, - 0 + (x * overlap[i].tile.width), - 420 + (y * overlap[i].tile.height), - overlap[i].tile.width, - overlap[i].tile.height - ); - - if (overlap[i].tile.collideNone == false) - { - game.context.fillRect(0 + (x * overlap[i].tile.width), 420 + (y * overlap[i].tile.height), overlap[i].tile.width, overlap[i].tile.height); - } - - x++; - - if (x == overlap[0].tw) - { - x = 0; - y++; - } - } - } - - game.context.restore(); - */ - - // game.debug.geom(sprite.body.hullX); - -} diff --git a/examples/wip/misc/wip3.js b/examples/wip/misc/wip3.js deleted file mode 100644 index 0cba994ed..000000000 --- a/examples/wip/misc/wip3.js +++ /dev/null @@ -1,188 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level3', 'assets/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tiles', 'assets/maps/cybernoid.png', 16, 16); - // game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - game.load.image('phaser', 'assets/sprites/space-baddie.png'); - -} - -var map; -var tileset; -var layer; -var cursors; -var overlap; -var sprite; - -function create() { - - game.stage.backgroundColor = '#3d3d3d'; - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = new Phaser.Tilemap(game, 'level3'); - - // A Tileset is a single image containing a strip of tiles. Each tile is broken down into its own Phaser.Tile object on import. - // You can set properties on the Tile objects, such as collision, n-way movement and meta data. - // A Tilemap uses a Tileset to render. The indexes in the map corresponding to the Tileset indexes. - // This way multiple levels can share the same single Tileset without requiring one each. - tileset = game.cache.getTileset('tiles'); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - tileset.setCollisionRange(0, tileset.total - 1, true, true, true, true); - - // And this turns off collision on the only tile we don't want collision on :) - tileset.setCollision(6, false, false, false, false); - tileset.setCollision(34, false, false, false, false); - tileset.setCollision(35, false, false, false, false); - - // A TilemapLayer consists of an x,y coordinate (position), a width and height, a Tileset and a Tilemap which it uses for map data. - // The x/y coordinates are in World space and you can place the tilemap layer anywhere in the world. - // The width/height is the rendered size of the layer in pixels, not the size of the map data itself. - - // This one gives tileset as a string, the other an object - // layer = new Phaser.TilemapLayer(game, 0, 0, 800, 400, tileset, map, 0); - layer = new Phaser.TilemapLayer(game, 0, 0, 400, 200, tileset, map, 0); - layer.sprite.scale.setTo(2, 2); - - // layer.sprite.anchor.setTo(0.5, 0.5); - - game.world.add(layer.sprite); - - // This is a bit nuts, ought to find a way to automate it, but it looks cool :) - map.debugMap = [ '#000000', - '#e40058', '#e40058', '#e40058', '#80d010', '#bcbcbc', '#e40058', '#000000', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc', '#e40058', '#e40058', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#80d010', '#80d010', '#80d010', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#80d010', '#0070ec', - '#0070ec', '#24188c', '#24188c', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#80d010', '#80d010', '#80d010', '#e40058', - '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#80d010', '#bcbcbc', '#80d010', '#000000', '#80d010', - '#80d010', '#80d010', '#bcbcbc', '#e40058', '#80d010', '#80d010', '#e40058', '#e40058', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc' - ]; - - // map.dump(); - - // layer.sprite.scale.setTo(2, 2); - - // Works a treat :) - // game.add.sprite(320, 0, layer.texture, layer.frame); - // game.add.sprite(0, 200, layer.texture, layer.frame); - // game.add.sprite(320, 200, layer.texture, layer.frame); - - // game.world.setBounds(0, 0, 2000, 2000); - // game.camera.x = 400; - - sprite = game.add.sprite(200, 80, 'phaser'); - // sprite.x = 140; - // sprite.y = 40; - - //sprite.scale.setTo(2, 2); - - - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - sprite.body.velocity.setTo(0, 0); - - // layer.sprite.angle += 0.5; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -100; - // layer.y -= 4; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 100; - // layer.y += 4; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -100; - // layer.x -= 4; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 100; - // layer.x += 4; - } - - // getTiles: function (x, y, width, height, collides, layer) { - overlap = layer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true); - - if (overlap.length > 1) - { - // console.log('%c ', 'background: #000000') - for (var i = 1; i < overlap.length; i++) - { - game.physics.separateTile(sprite.body, overlap[i]); - } - } - -} - -function render() { - - layer.render(); - - game.debug.spriteBody(sprite); - - game.debug.spriteInfo(sprite, 32, 450); - // game.debug.cameraInfo(game.camera, 32, 32); - - /* - game.context.save(); - game.context.setTransform(1, 0, 0, 1, 0, 0); - - - game.context.fillStyle = 'rgba(255, 0, 0, 0.5)'; - - if (overlap.length > 1) - { - var x = 0; - var y = 0; - - for (var i = 1; i < overlap.length; i++) - { - game.context.drawImage( - overlap[i].tile.tileset.image, - overlap[i].tile.x, - overlap[i].tile.y, - overlap[i].tile.width, - overlap[i].tile.height, - 0 + (x * overlap[i].tile.width), - 420 + (y * overlap[i].tile.height), - overlap[i].tile.width, - overlap[i].tile.height - ); - - if (overlap[i].tile.collideNone == false) - { - game.context.fillRect(0 + (x * overlap[i].tile.width), 420 + (y * overlap[i].tile.height), overlap[i].tile.width, overlap[i].tile.height); - } - - x++; - - if (x == overlap[0].tw) - { - x = 0; - y++; - } - } - } - - game.context.restore(); - */ - - // game.debug.geom(sprite.body.hullX); - -} diff --git a/examples/wip/misc/wip4.js b/examples/wip/misc/wip4.js deleted file mode 100644 index 11c22847e..000000000 --- a/examples/wip/misc/wip4.js +++ /dev/null @@ -1,197 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level3', 'assets/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.tileset('tiles', 'assets/maps/cybernoid.png', 16, 16); - game.load.image('phaser', 'assets/sprites/phaser-ship.png'); - -} - -var map; -var tileset; -var layer; -var cursors; -var overlap; -var sprite; - -function create() { - - game.stage.backgroundColor = '#3d3d3d'; - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = new Phaser.Tilemap(game, 'level3'); - - // A Tileset is a single image containing a strip of tiles. Each tile is broken down into its own Phaser.Tile object on import. - // You can set properties on the Tile objects, such as collision, n-way movement and meta data. - // A Tilemap uses a Tileset to render. The indexes in the map corresponding to the Tileset indexes. - // This way multiple levels can share the same single Tileset without requiring one each. - tileset = game.cache.getTileset('tiles'); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - tileset.setCollisionRange(0, tileset.total - 1, true, true, true, true); - - // And this turns off collision on the only tile we don't want collision on :) - tileset.setCollision(6, false, false, false, false); - tileset.setCollision(31, false, false, false, false); - tileset.setCollision(34, false, false, false, false); - tileset.setCollision(35, false, false, false, false); - tileset.setCollision(46, false, false, false, false); - - // A TilemapLayer consists of an x,y coordinate (position), a width and height, a Tileset and a Tilemap which it uses for map data. - // The x/y coordinates are in World space and you can place the tilemap layer anywhere in the world. - // The width/height is the rendered size of the layer in pixels, not the size of the map data itself. - - // This one gives tileset as a string, the other an object - layer = new Phaser.TilemapLayer(game, 0, 0, 800, 600, tileset, map, 0); - // layer = new Phaser.TilemapLayer(game, 0, 0, 400, 200, tileset, map, 0); - // layer.sprite.scale.setTo(2, 2); - - // layer.sprite.anchor.setTo(0.5, 0.5); - - layer.resizeWorld(); - - game.world.add(layer.sprite); - - // This is a bit nuts, ought to find a way to automate it, but it looks cool :) - map.debugMap = [ '#000000', - '#e40058', '#e40058', '#e40058', '#80d010', '#bcbcbc', '#e40058', '#000000', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc', '#e40058', '#e40058', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#80d010', '#80d010', '#80d010', '#0070ec', '#0070ec', '#80d010', '#80d010', '#80d010', '#80d010', '#0070ec', - '#0070ec', '#24188c', '#24188c', '#80d010', '#80d010', '#80d010', '#bcbcbc', '#80d010', '#80d010', '#80d010', '#e40058', - '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#e40058', '#bcbcbc', '#80d010', '#bcbcbc', '#80d010', '#000000', '#80d010', - '#80d010', '#80d010', '#bcbcbc', '#e40058', '#80d010', '#80d010', '#e40058', '#e40058', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#0070ec', '#0070ec', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', '#bcbcbc', - '#bcbcbc', '#bcbcbc' - ]; - - // map.dump(); - - // layer.sprite.scale.setTo(2, 2); - - // Works a treat :) - // game.add.sprite(320, 0, layer.texture, layer.frame); - // game.add.sprite(0, 200, layer.texture, layer.frame); - // game.add.sprite(320, 200, layer.texture, layer.frame); - - // game.world.setBounds(0, 0, 2000, 2000); - // game.camera.x = 400; - - sprite = game.add.sprite(450, 80, 'phaser'); - sprite.anchor.setTo(0.5, 0.5); - // sprite.x = 140; - // sprite.y = 40; - - //sprite.scale.setTo(2, 2); - - // sprite.body.gravity.y = 100; - // sprite.body.bounce.x = 0.5; - // sprite.body.bounce.y = 0.2; - - game.camera.follow(sprite); - game.camera.deadzone = new Phaser.Rectangle(160, 160, layer.renderWidth-320, layer.renderHeight-320); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - layer.update(); - - // getTiles: function (x, y, width, height, collides, layer) { - overlap = layer.getTiles(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height, true); - - if (overlap.length > 1) - { - for (var i = 1; i < overlap.length; i++) - { - game.physics.separateTile(sprite.body, overlap[i]); - } - } - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -150; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 150; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -150; - sprite.scale.x = -1; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 150; - sprite.scale.x = 1; - } - - -} - -function render() { - - layer.render(); - - // game.debug.spriteBody(sprite); - - // game.debug.spriteInfo(sprite, 32, 450); - - // game.debug.cameraInfo(game.camera, 32, 32); - - /* - game.context.save(); - game.context.setTransform(1, 0, 0, 1, 0, 0); - - - game.context.fillStyle = 'rgba(255, 0, 0, 0.5)'; - - if (overlap.length > 1) - { - var x = 0; - var y = 0; - - for (var i = 1; i < overlap.length; i++) - { - game.context.drawImage( - overlap[i].tile.tileset.image, - overlap[i].tile.x, - overlap[i].tile.y, - overlap[i].tile.width, - overlap[i].tile.height, - 0 + (x * overlap[i].tile.width), - 420 + (y * overlap[i].tile.height), - overlap[i].tile.width, - overlap[i].tile.height - ); - - if (overlap[i].tile.collideNone == false) - { - game.context.fillRect(0 + (x * overlap[i].tile.width), 420 + (y * overlap[i].tile.height), overlap[i].tile.width, overlap[i].tile.height); - } - - x++; - - if (x == overlap[0].tw) - { - x = 0; - y++; - } - } - } - - game.context.restore(); - */ - - // game.debug.geom(game.camera.deadzone, 'rgba(0,200,0,0.5)'); - -} diff --git a/examples/wip/misc/world.js b/examples/wip/misc/world.js deleted file mode 100644 index 95bbd0b6a..000000000 --- a/examples/wip/misc/world.js +++ /dev/null @@ -1,39 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - -} - -var sprite; - -function create() { - - game.stage.backgroundColor = '#124184'; - - game.physics.gravity.y = 200; - - sprite = game.add.sprite(200, 250, 'gameboy', 4); - sprite.name = 'green'; - sprite.body.collideWorldBounds = true; - // sprite.anchor.setTo(0.5, 0.5); - - sprite.body.bounce.setTo(0.9, 0.9); - sprite.body.velocity.x = 150; - -} - -function update() { - - // sprite.worldTransform[2] += 1; - -} - -function render() { - - game.debug.bodyInfo(sprite, 32, 32); - game.debug.physicsBody(sprite.body); - -} diff --git a/examples/wip/mouse.js b/examples/wip/mouse.js deleted file mode 100644 index 6735d71dd..000000000 --- a/examples/wip/mouse.js +++ /dev/null @@ -1,102 +0,0 @@ -function distanceBetween(point1, point2) { - return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2)); -} -function angleBetween(point1, point2) { - return Math.atan2( point2.x - point1.x, point2.y - point1.y ); -} - -var isDrawing, lastPoint; - - - -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('mushroom', 'assets/sprites/chunk.png'); - -} - -var mushroom; -var texture; -var image; - -var down; -var p; - -function create() { - - texture = game.add.renderTexture(800, 600, 'mousetrail', true); - - // We create a sprite (rather than using the factory) so it doesn't get added to the display, as we only need its texture data. - mushroom = new Phaser.Sprite(game, 0, 0, 'mushroom'); - mushroom.anchor.setTo(0.5, 0.5); - - // This is the sprite that is drawn to the display. We've given it the renderTexture as its texture. - image = game.add.image(0, 0, texture); - - domElement = document.getElementById('phaser-example'); - - p = new Phaser.Point(); - - domElement.addEventListener('mousemove', onMouseMove, true); - domElement.addEventListener('mousedown', onMouseDown, true); - // domElement.addEventListener('mouseout', onMouseOut, true); - domElement.addEventListener('mouseup', onMouseUp, true); - - texture.render(mushroom, p, false); - -} - -function onMouseDown(e) { - isDrawing = true; - lastPoint = { x: e.clientX, y: e.clientY }; -} - -function onMouseUp(e) { - isDrawing = false; -} - -function onMouseMove(e) { - - if (!isDrawing) return; - - var currentPoint = { x: e.clientX, y: e.clientY }; - var dist = distanceBetween(lastPoint, currentPoint); - var angle = angleBetween(lastPoint, currentPoint); - - for (var i = 0; i < dist; i+=5) { - x = lastPoint.x + (Math.sin(angle) * i) - 25; - y = lastPoint.y + (Math.cos(angle) * i) - 25; - p.set(x, y); - texture.render(mushroom, p, false); - - // ctx.beginPath(); - // ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false); - // ctx.closePath(); - // ctx.fill(); - // ctx.stroke(); - } - - lastPoint = currentPoint; - -} - -function tint() { - - image.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - // if (down) - // { - // } - -} - -function render() { - -} diff --git a/examples/wip/mouse2.js b/examples/wip/mouse2.js deleted file mode 100644 index 0b0afa794..000000000 --- a/examples/wip/mouse2.js +++ /dev/null @@ -1,106 +0,0 @@ -function distanceBetween(point1, point2) { - return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2)); -} -function angleBetween(point1, point2) { - return Math.atan2( point2.x - point1.x, point2.y - point1.y ); -} - -var isDrawing, lastPoint; - - - -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('mushroom', 'assets/sprites/chunk.png'); - -} - -var mushroom; -var texture; -var image; - -var down; -var p; - -function create() { - - texture = game.add.renderTexture(800, 600, 'mousetrail', true); - - // We create a sprite (rather than using the factory) so it doesn't get added to the display, as we only need its texture data. - mushroom = new Phaser.Sprite(game, 0, 0, 'mushroom'); - mushroom.anchor.setTo(0.5, 0.5); - - // This is the sprite that is drawn to the display. We've given it the renderTexture as its texture. - image = game.add.image(0, 0, texture); - - domElement = document.getElementById('phaser-example'); - - p = new Phaser.Point(); - - // domElement.addEventListener('mousemove', onMouseMove, true); - // domElement.addEventListener('mousedown', onMouseDown, true); - // // domElement.addEventListener('mouseout', onMouseOut, true); - // domElement.addEventListener('mouseup', onMouseUp, true); - - game.input.mouse.mouseDownCallback = onMouseDown; - game.input.mouse.mouseUpCallback = onMouseUp; - game.input.mouse.mouseMoveCallback = onMouseMove; - - texture.render(mushroom, p, false); - -} - -function onMouseDown(e) { - isDrawing = true; - lastPoint = { x: e.clientX, y: e.clientY }; -} - -function onMouseUp(e) { - isDrawing = false; -} - -function onMouseMove(e) { - - if (!isDrawing) return; - - var currentPoint = { x: e.clientX, y: e.clientY }; - var dist = distanceBetween(lastPoint, currentPoint); - var angle = angleBetween(lastPoint, currentPoint); - - for (var i = 0; i < dist; i+=5) { - x = lastPoint.x + (Math.sin(angle) * i) - 25; - y = lastPoint.y + (Math.cos(angle) * i) - 25; - p.set(x, y); - texture.render(mushroom, p, false); - - // ctx.beginPath(); - // ctx.arc(x+10, y+10, 20, false, Math.PI * 2, false); - // ctx.closePath(); - // ctx.fill(); - // ctx.stroke(); - } - - lastPoint = currentPoint; - -} - -function tint() { - - image.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - // if (down) - // { - // } - -} - -function render() { - -} diff --git a/examples/wip/ninja aabb vs aabb.js b/examples/wip/ninja aabb vs aabb.js deleted file mode 100644 index d3cf1ed79..000000000 --- a/examples/wip/ninja aabb vs aabb.js +++ /dev/null @@ -1,77 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('block', 'assets/sprites/block.png'); - game.load.spritesheet('ninja-tiles', 'assets/physics/ninja-tiles128.png', 128, 128, 34); - -} - -var sprite1; -var sprite2; -var tile; -var cursors; - -function create() { - - game.physics.startSystem(Phaser.Physics.NINJA); - - // game.physics.ninja.gravity = 6; - - // sprite1 = game.add.sprite(200, 100, 'block'); - sprite1 = game.add.sprite(200, 500, 'block'); - sprite1.name = 'blockA'; - - sprite2 = game.add.sprite(600, 100, 'block'); - sprite2.name = 'blockB'; - - // game.physics.ninja.enableAABB([sprite1]); - game.physics.ninja.enableAABB([sprite1, sprite2]); - - tile = game.add.sprite(600, 480, 'ninja-tiles', 3); - game.physics.ninja.enableTile(tile, tile.frame); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.ninja.collide(sprite1, sprite2); - game.physics.ninja.collide(sprite1, tile); - game.physics.ninja.collide(sprite2, tile); - - sprite1.body.moveRight(5); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(20); - } - - // if (cursors.up.isDown && sprite1.body.touching.down) - if (cursors.up.isDown) - { - // sprite1.body.moveUp(1000); - sprite1.body.moveUp(30); - } - // else if (cursors.down.isDown) - // { - // sprite1.body.moveDown(20); - // } - -} - -function render() { - - game.debug.text('left: ' + sprite1.body.touching.left, 32, 32); - game.debug.text('right: ' + sprite1.body.touching.right, 256, 32); - game.debug.text('up: ' + sprite1.body.touching.up, 32, 64); - game.debug.text('down: ' + sprite1.body.touching.down, 256, 64); - -} diff --git a/examples/wip/ninja aabb vs aabb2.js b/examples/wip/ninja aabb vs aabb2.js deleted file mode 100644 index a46d5f0f2..000000000 --- a/examples/wip/ninja aabb vs aabb2.js +++ /dev/null @@ -1,92 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('block', 'assets/sprites/block.png'); - game.load.spritesheet('ninja-tiles', 'assets/physics/ninja-tiles128.png', 128, 128, 34); - -} - -var sprite1; -var sprite2; -var tile; -var cursors; - - -function create() { - - game.physics.startSystem(Phaser.Physics.NINJA); - - sprite1 = game.add.sprite(100, 450, 'block'); - sprite1.name = 'blockA'; - - sprite2 = game.add.sprite(600, 450, 'block'); - sprite2.name = 'blockB'; - sprite2.tint = Math.random() * 0xffffff; - - game.physics.ninja.enableAABB([sprite1, sprite2]); - - // sprite1.body.immovable = true; - sprite1.body.immovable = false; - // sprite2.body.immovable = true; - sprite2.body.immovable = false; - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.add(t, this); - -} - -function t() { - - sprite1.body.shape.oldpos.x = sprite1.body.shape.pos.x - 30; - sprite2.body.shape.oldpos.x = sprite2.body.shape.pos.x + 20; - -} - -function update() { - - // Whichever one goes first utterly changes how the collision happens! - game.physics.ninja.collide(sprite1, sprite2); - // game.physics.ninja.collide(sprite2, sprite1); - - - - - // game.physics.ninja.collide(sprite1, tile); - // game.physics.ninja.collide(sprite2, tile); - - // sprite1.body.moveRight(5); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(20); - } - - // if (cursors.up.isDown && sprite1.body.touching.down) - if (cursors.up.isDown) - { - // sprite1.body.moveUp(1000); - sprite1.body.moveUp(30); - } - // else if (cursors.down.isDown) - // { - // sprite1.body.moveDown(20); - // } - -} - -function render() { - - game.debug.text('left: ' + sprite1.body.touching.left, 32, 32); - game.debug.text('right: ' + sprite1.body.touching.right, 256, 32); - game.debug.text('up: ' + sprite1.body.touching.up, 32, 64); - game.debug.text('down: ' + sprite1.body.touching.down, 256, 64); - -} diff --git a/examples/wip/ninja overlap.js b/examples/wip/ninja overlap.js deleted file mode 100644 index a81438359..000000000 --- a/examples/wip/ninja overlap.js +++ /dev/null @@ -1,80 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('gameboy', 'assets/sprites/gameboy_seize_color_40x60.png', 40, 60); - game.load.image('diamond', 'assets/sprites/diamond.png'); - game.load.image('sky', 'assets/skies/cavern1.png'); - -} - -var sprite1; -var cursors; -var diamonds; - -function create() { - - game.add.image(0, 0, 'sky'); - - game.physics.startSystem(Phaser.Physics.NINJA); - - game.physics.ninja.gravity = 0; - - sprite1 = game.add.sprite(500, 200, 'gameboy'); - game.physics.ninja.enableAABB(sprite1); - - diamonds = game.add.group(); - diamonds.enableBody = true; - - for (var i = 0; i < 20; i++) - { - var d = diamonds.create(game.world.randomX, game.world.randomY, 'diamond'); - } - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function collisionHandler(s, d) { - - d.kill(); - -} - -function update() { - - game.physics.arcade.overlap(sprite1, diamonds, collisionHandler, null, this); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(10); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(10); - } - - if (cursors.up.isDown) - { - sprite1.body.moveUp(10); - } - else if (cursors.down.isDown) - { - sprite1.body.moveDown(10); - } - -} - -function render() { - - game.debug.rectangle(sprite1.body); - - for (var i = 0; i < diamonds.length; i++) - { - game.debug.rectangle(diamonds.children[i].body); - } - - -} diff --git a/examples/wip/ninja tilemap.js b/examples/wip/ninja tilemap.js deleted file mode 100644 index f287e526e..000000000 --- a/examples/wip/ninja tilemap.js +++ /dev/null @@ -1,100 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/ninja-tilemap.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ball', 'assets/sprites/shinyball.png'); - game.load.image('sky', 'assets/skies/sky2.png'); - game.load.image('kenney', 'assets/tilemaps/tiles/kenney.png'); - -} - -var sprite1; -var cursors; -var map; -var layer; -var tiles; - -function create() { - - var sky = game.add.image(0, 0, 'sky'); - sky.fixedToCamera = true; - - // Activate the Ninja physics system - game.physics.startSystem(Phaser.Physics.NINJA); - - map = game.add.tilemap('map'); - - map.addTilesetImage('kenney'); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - var slopeMap = { '32': 1, '77': 1, '95': 2, '36': 3, '137': 3, '140': 2 }; - - tiles = game.physics.ninja.convertTilemap(map, layer, slopeMap); - - sprite1 = game.add.sprite(50, 50, 'ball'); - // game.physics.ninja.enableAABB(sprite1); - game.physics.ninja.enableCircle(sprite1, sprite1.width / 2); - - // A little more bounce - sprite1.body.bounce = 0.5; - - game.camera.follow(sprite1); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - for (var i = 0; i < tiles.length; i++) - { - sprite1.body.circle.collideCircleVsTile(tiles[i].tile); - // sprite1.body.aabb.collideAABBVsTile(tiles[i].tile); - } - - // game.physics.ninja.collide(sprite1, tiles); - - // sprite1.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(20); - } - - if (cursors.up.isDown) - { - sprite1.body.moveUp(20); - } - else if (cursors.down.isDown) - { - sprite1.body.moveUp(20); - } - -} - -function render() { - - - // game.debug.text(sprite1.body.shape.velocity.x, 32, 32); - // game.debug.text(sprite1.body.shape.velocity.y, 32, 64); - // game.debug.text(game.math.radToDeg(sprite1.body.angle), 32, 96); - - // tile1.render(game.context, 'ninja-tiles'); - // tile2.render(game.context, 'ninja-tiles'); - - // game.debug.geom(sprite1.body, 'rgba(0,255,0,0.4)', true, 1); - - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - -} diff --git a/examples/wip/ninja tilesprite.js b/examples/wip/ninja tilesprite.js deleted file mode 100644 index d15e00709..000000000 --- a/examples/wip/ninja tilesprite.js +++ /dev/null @@ -1,77 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -var ball; -var sprite; -var cursors; - -function create() { - - game.physics.startSystem(Phaser.Physics.NINJA); - - sprite = game.add.tileSprite(100, 100, 200, 200, 'starfield'); - sprite.autoScroll(0, 100); - - game.physics.ninja.enableAABB(sprite); - // game.physics.ninja.enableTile(sprite, 14); - - // By default Tiles have gravity and world collision disabled (as they are mostly used for platforms and the likes) - // We re-enable it here - // sprite.body.gravityScale = 1; - // sprite.body.collideWorldBounds = true; - - ball = game.add.sprite(400, 0, 'ball'); - - // Enable the physics body for the Ninja physics system - game.physics.ninja.enableCircle(ball, ball.width / 2); - - // A little more bounce - ball.body.bounce = 0.5; - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.ninja.collide(sprite, ball); - - if (cursors.left.isDown) - { - sprite.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite.body.moveRight(20); - } - - if (cursors.up.isDown) - { - sprite.body.moveUp(20); - } - else if (cursors.down.isDown) - { - sprite.body.moveDown(20); - } - -} - -function render() { - - var r = new Phaser.Rectangle(sprite.body.x - (sprite.body.width / 2), sprite.body.y - (sprite.body.height / 2), sprite.body.width, sprite.body.height); - - // game.debug.text(sprite.body.x, 32, 32); - // game.debug.text(sprite.body.y, 32, 64); - // game.debug.text(sprite.body.width, 128, 32); - // game.debug.text(sprite.body.height, 128, 64); - // game.debug.geom(r, 'rgba(0,255,0,0.4)', true); - -} diff --git a/examples/wip/ninja1.js b/examples/wip/ninja1.js deleted file mode 100644 index 8f3eab2f7..000000000 --- a/examples/wip/ninja1.js +++ /dev/null @@ -1,122 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('ninja-tiles', 'assets/physics/ninja-tiles128.png', 128, 128, 34); - game.load.image('a', 'assets/sprites/firstaid.png'); - -} - -var sprite1; -var cursors; - -var tile1; -var tile2; - -var t; -var running = false; - -function create() { - - game.stage.smoothed = true; - - // Activate the Ninja physics system - game.physics.startSystem(Phaser.Physics.NINJA); - - // game.physics.ninja.gravity = 0.1; - - sprite1 = game.add.sprite(500, 200, 'a'); - - // Enable the physics body for the Ninja physics system - // By default it will create an AABB body for the sprite - game.physics.ninja.enableAABB(sprite1); - - // But you can change it to either a Tile or a Circle - tile1 = game.add.sprite(0, 500, 'ninja-tiles', 14); - tile1.width = 100; - tile1.height = 100; - - game.physics.ninja.enableTile(tile1, tile1.frame); - - // sprite1.body.aabb.friction = 0; - - // tile1 = new Phaser.Physics.Ninja.Tile(game.physics.ninja, 100, 500, 100, 100, Phaser.Physics.Ninja.Tile.SLOPE_45DEGpn); - // tile1 = new Phaser.Physics.Ninja.Tile(game.physics.ninja, 100, 500, 100, 100, 15); - // tile2 = new Phaser.Physics.Ninja.Tile(game.physics.ninja, 300, 500, 100, 100, 7); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function collisionHandler() { - game.stage.backgroundColor = 0xff0000; -} - -function update() { - - game.physics.ninja.collide(sprite1, tile1, collisionHandler, null, this); - - tile1.body.moveRight(1); - - /* - if (cursors.up.isDown && !running) - { - running = true; - t = Date.now(); - } - - sprite1.body.setZeroVelocity(); - - if (running) - { - sprite1.body.moveRight(100); - - if (sprite1.body.x >= 200) - { - var ms = Date.now() - t; - console.log('100px in ', ms); - running = false; - sprite1.body.setZeroVelocity(); - } - } - */ - - // sprite1.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(20); - } - - if (cursors.up.isDown) - { - sprite1.body.moveUp(20); - } - else if (cursors.down.isDown) - { - sprite1.body.moveUp(20); - } - -} - -function render() { - - // game.debug.text(sprite1.body.shape.velocity.x, 32, 32); - // game.debug.text(sprite1.body.shape.velocity.y, 32, 64); - // game.debug.text(game.math.radToDeg(sprite1.body.angle), 32, 96); - - // tile1.render(game.context, 'ninja-tiles'); - // tile2.render(game.context, 'ninja-tiles'); - - // game.debug.geom(sprite1.body, 'rgba(0,255,0,0.4)', true, 1); - - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - -} diff --git a/examples/wip/ninja2.js b/examples/wip/ninja2.js deleted file mode 100644 index 99976e7cd..000000000 --- a/examples/wip/ninja2.js +++ /dev/null @@ -1,117 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('ninja-tiles', 'assets/physics/ninja-tiles.png', 128, 128, 34); - game.load.image('a', 'assets/sprites/firstaid.png'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - -} - -var sprite1; -var cursors; - -var tile1; -var tile2; - -var t; -var running = false; - -function create() { - - game.stage.smoothed = true; - - // Activate the Ninja physics system - game.physics.startSystem(Phaser.Physics.NINJA); - - // game.physics.ninja.gravity = 0.1; - - sprite1 = game.add.sprite(102, 200, 'ball'); - - // Enable the physics body for the Ninja physics system - // By default it will create an AABB body for the sprite - game.physics.ninja.enableCircle(sprite1, sprite1.width / 2); - - // But you can change it to either a Tile or a Circle - tile1 = game.add.sprite(100, 500, 'ninja-tiles', 14); - tile1.width = 100; - tile1.height = 100; - - game.physics.ninja.enableTile(tile1, 14); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function collisionHandler() { - game.stage.backgroundColor = 0xff0000; -} - -function update() { - - game.physics.ninja.collide(sprite1, tile1, collisionHandler, null, this); - - // tile1.body.moveRight(1); - - /* - if (cursors.up.isDown && !running) - { - running = true; - t = Date.now(); - } - - sprite1.body.setZeroVelocity(); - - if (running) - { - sprite1.body.moveRight(100); - - if (sprite1.body.x >= 200) - { - var ms = Date.now() - t; - console.log('100px in ', ms); - running = false; - sprite1.body.setZeroVelocity(); - } - } - */ - - // sprite1.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(20); - } - - if (cursors.up.isDown) - { - sprite1.body.moveUp(20); - } - else if (cursors.down.isDown) - { - sprite1.body.moveUp(20); - } - -} - -function render() { - - game.debug.text(sprite1.body.shape.velocity.x, 32, 32); - game.debug.text(sprite1.body.shape.velocity.y, 32, 64); - game.debug.text(game.math.radToDeg(sprite1.body.angle), 32, 96); - - // tile1.render(game.context, 'ninja-tiles'); - // tile2.render(game.context, 'ninja-tiles'); - - // game.debug.geom(sprite1.body, 'rgba(0,255,0,0.4)', true, 1); - - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - -} diff --git a/examples/wip/ninja3.js b/examples/wip/ninja3.js deleted file mode 100644 index 608e51542..000000000 --- a/examples/wip/ninja3.js +++ /dev/null @@ -1,107 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('ninja-tiles', 'assets/physics/ninja-tiles32.png', 32, 32, 34); - game.load.json('level', 'assets/physics/ninja-test-level.json'); - game.load.image('ball', 'assets/sprites/shinyball.png'); - game.load.image('sky', 'assets/skies/sky2.png'); - -} - -var sprite1; -var tiles; -var cursors; - -function create() { - - var sky = game.add.image(0, 0, 'sky'); - sky.fixedToCamera = true; - - // Activate the Ninja physics system - game.physics.startSystem(Phaser.Physics.NINJA); - - sprite1 = game.add.sprite(100, 0, 'ball'); - - // Enable the physics body for the Ninja physics system - game.physics.ninja.enableCircle(sprite1, sprite1.width / 2); - - // A little more bounce - sprite1.body.bounce = 0.5; - - var layer = game.cache.getJSON('level').layers[0]; - var i = 0; - var data = layer.data; - var width = layer.width; - var height = layer.height; - - // Resize the world to match - game.world.setBounds(0, 0, width * 32, height * 32); - - tiles = game.add.group(); - - var tile; - - for (var y = 0; y < height; y++) - { - for (var x = 0; x < width; x++) - { - if (data[i] > 0) - { - tile = tiles.create(x * 32, y * 32, 'ninja-tiles', data[i] - 1); - game.physics.ninja.enableTile(tile, tile.frame); - } - - i++; - } - } - - cursors = game.input.keyboard.createCursorKeys(); - - game.camera.follow(sprite1); - -} - -function update() { - - game.physics.ninja.collide(sprite1, tiles); - - // sprite1.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - sprite1.body.moveLeft(20); - } - else if (cursors.right.isDown) - { - sprite1.body.moveRight(20); - } - - if (cursors.up.isDown) - { - sprite1.body.moveUp(20); - } - else if (cursors.down.isDown) - { - sprite1.body.moveUp(20); - } - -} - -function render() { - - // game.debug.text(sprite1.body.shape.velocity.x, 32, 32); - // game.debug.text(sprite1.body.shape.velocity.y, 32, 64); - // game.debug.text(game.math.radToDeg(sprite1.body.angle), 32, 96); - - // tile1.render(game.context, 'ninja-tiles'); - // tile2.render(game.context, 'ninja-tiles'); - - // game.debug.geom(sprite1.body, 'rgba(0,255,0,0.4)', true, 1); - - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - // game.debug.geom(tile1, 'rgba(0,255,0,0.4)', true, 1); - -} diff --git a/examples/wip/no-scale.js b/examples/wip/no-scale.js deleted file mode 100644 index 8bddac5b1..000000000 --- a/examples/wip/no-scale.js +++ /dev/null @@ -1,59 +0,0 @@ - -var game = new Phaser.Game(1024, 672, Phaser.CANVAS, 'phaser-example', { init: init, preload: preload, create: create, update: update, render: render }); - -function init() { - - game.scale.scaleMode = Phaser.ScaleManager.NO_SCALE; - // game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; - game.scale.forceOrientation(true, false); - game.scale.enterIncorrectOrientation.add(enterIncorrectOrientation, game); - game.scale.leaveIncorrectOrientation.add(leaveIncorrectOrientation, game); - game.scale.setScreenSize(true); - - game.stage.backgroundColor = 0x004400; - -} - -function preload() { - - game.load.image('pic', 'assets/pics/remember-me.jpg'); - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; -var anim; - -function create() { - - game.add.image(0, 0, 'pic'); - - mummy = game.add.sprite(300, 200, 'mummy', 5); - - anim = mummy.animations.add('walk'); - - anim.play(20, true); - -} - -function enterIncorrectOrientation () { - - // game.stage.backgroundColor = 0xff0000; - -} - -function leaveIncorrectOrientation () { - - // game.stage.backgroundColor = 0x000033; - -} - -function update() { - -} - -function render() { - - // game.debug.pointer(game.input.activePointer); - -} \ No newline at end of file diff --git a/examples/wip/p2 tilemap1.js b/examples/wip/p2 tilemap1.js deleted file mode 100644 index 91f10a16d..000000000 --- a/examples/wip/p2 tilemap1.js +++ /dev/null @@ -1,90 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('walls_1x2', 'assets/tilemaps/tiles/walls_1x2.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - game.load.image('player', 'assets/sprites/phaser-dude.png'); - game.load.image('box', 'assets/sprites/ufo.png'); - game.load.image('ship', 'assets/sprites/thrust_ship2.png'); - -} - -var ship; -var map; -var tileset; -var layer; -var p; -var b; -var cursors; -var box2; -var dump; - -function create() { - - game.physics.startSystem(Phaser.Physics.P2JS); - - game.stage.backgroundColor = '#787878'; - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('walls_1x2'); - map.addTilesetImage('tiles2'); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - map.setCollisionBetween(1, 12); - - // layer.debug = true; - - dump = game.physics.p2.convertTilemap(map, layer); - - box2 = game.add.sprite(200, 200, 'box'); - game.physics.p2.enable(box2); - box2.body.fixedRotation = true; - - game.camera.follow(box2); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - box2.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - box2.body.moveLeft(200); - } - else if (cursors.right.isDown) - { - box2.body.moveRight(200); - } - - if (cursors.up.isDown) - { - box2.body.moveUp(200); - } - else if (cursors.down.isDown) - { - box2.body.moveDown(200); - } - -} - -function render() { - - // for (var i = 0, len = dump.length; i < len; i++) - // { - // game.debug.physicsBody(dump[i]); - // } - -} diff --git a/examples/wip/p21.js b/examples/wip/p21.js deleted file mode 100644 index 62c754482..000000000 --- a/examples/wip/p21.js +++ /dev/null @@ -1,130 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }, false); - -function preload() { - - game.load.image('box', 'assets/sprites/block.png'); - -} - -var world; - -var box; -var box2; - -var boxShape; -var boxBody; - -var boxShape2; -var boxBody2; - -var planeShape; -var planeBody; - -function p2px(v) { - return v *= -20; -} - -function px2p(v) { - return v * -0.05; -} - -function create() { - - game.renderer.roundPixels = true; - - box = game.add.image(300, 200, 'box'); - box.anchor.set(0.5); - - box2 = game.add.image(300, 10, 'box'); - box2.anchor.set(0.5); - - world = new p2.World(); - - boxShape = new p2.Rectangle(px2p(box.width), px2p(box.height)); - boxBody = new p2.Body({ mass: 1, position:[px2p(box.x), px2p(box.y)], angularVelocity: 1 }); - boxBody.addShape(boxShape); - - boxShape2 = new p2.Rectangle(px2p(box2.width), px2p(box2.height)); - boxBody2 = new p2.Body({ mass: 1, position:[px2p(box2.x), px2p(box2.y)], angularVelocity: 1 }); - boxBody2.addShape(boxShape2); - - - world.addBody(boxBody); - world.addBody(boxBody2); - - // Add a plane - planeShape = new p2.Plane(); - planeBody = new p2.Body({ mass: 0, position:[0, px2p(550)] }); - // planeBody = new p2.Body(); - planeBody.addShape(planeShape); - world.addBody(planeBody); - -} - -function update() { - - // Move physics bodies forward in time - world.step(1/60); - - box.x = p2px(boxBody.position[0]); - box.y = p2px(boxBody.position[1]); - box.rotation = boxBody.angle; // Rotate to the box body frame - - box2.x = p2px(boxBody2.position[0]); - box2.y = p2px(boxBody2.position[1]); - box2.rotation = boxBody2.angle; // Rotate to the box body frame - -} - -function render() { - - // game.debug.text('x: ' + p2px(boxBody.position[0]), 32, 32); - // game.debug.text('y: ' + p2px(boxBody.position[1]), 32, 64); - // game.debug.text('r: ' + boxBody.angle, 32, 96); - - // drawbox(); - -} - -function drawbox() { - - var ctx = game.context; - - ctx.save(); - ctx.translate(game.width/2, game.height/2); // Translate to the center - ctx.scale(50, -50); // Zoom in and flip y axis - - ctx.lineWidth = 0.05; - ctx.strokeStyle = 'rgb(255,255,255)'; - - - ctx.beginPath(); - var x = boxBody.position[0], - y = boxBody.position[1]; - ctx.save(); - ctx.translate(x, y); // Translate to the center of the box - ctx.rotate(boxBody.angle); // Rotate to the box body frame - ctx.rect(-boxShape.width/2, -boxShape.height/2, boxShape.width, boxShape.height); - ctx.stroke(); - ctx.closePath(); - // ctx.restore(); - - // ctx.save(); - // ctx.translate(game.width/2, game.height/2); // Translate to the center - // ctx.scale(50, -50); // Zoom in and flip y axis - - // ctx.lineWidth = 0.05; - // ctx.strokeStyle = 'rgb(255,255,255)'; - // ctx.beginPath(); - - // var y = planeBody.position[1]; - // ctx.rotate(0); // Rotate to the box body frame - // ctx.moveTo(-game.width, y); - // ctx.lineTo( game.width, y); - // ctx.stroke(); - - // ctx.closePath(); - ctx.restore(); -} - diff --git a/examples/wip/p22.js b/examples/wip/p22.js deleted file mode 100644 index 6e7600c0f..000000000 --- a/examples/wip/p22.js +++ /dev/null @@ -1,124 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('box', 'assets/sprites/block.png'); - -} - -var box; -var box2; -var cursors; - -function p2px(v) { - return v *= -20; -} - -function px2p(v) { - return v * -0.05; -} - -function create() { - - box = game.add.sprite(200, 0, 'box'); - - box2 = game.add.sprite(400, 0, 'box'); - box2.physicsEnabled = true; - - box2.body.setZeroDamping(); - - cursors = game.input.keyboard.createCursorKeys(); - - - // box2.body.mass = 2; - - /* - // Add a plane - planeShape = new p2.Plane(); - planeBody = new p2.Body({ mass: 0, position:[0, px2p(550)] }); - // planeBody = new p2.Body(); - planeBody.addShape(planeShape); - world.addBody(planeBody); - */ - -} - -function update() { - - box2.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - box2.body.moveLeft(200); - } - else if (cursors.right.isDown) - { - box2.body.moveRight(200); - } - - if (cursors.up.isDown) - { - box2.body.moveUp(200); - } - else if (cursors.down.isDown) - { - box2.body.moveDown(200); - } - -} - -function render() { - - game.debug.text('x: ' + box2.body.velocity.x, 32, 32); - game.debug.text('y: ' + box2.body.velocity.y, 32, 64); - - // game.debug.text('x: ' + p2px(boxBody.position[0]), 32, 32); - // game.debug.text('y: ' + p2px(boxBody.position[1]), 32, 64); - // game.debug.text('r: ' + boxBody.angle, 32, 96); - - // drawbox(); - -} - -function drawbox() { - - var ctx = game.context; - - ctx.save(); - ctx.translate(game.width/2, game.height/2); // Translate to the center - ctx.scale(50, -50); // Zoom in and flip y axis - - ctx.lineWidth = 0.05; - ctx.strokeStyle = 'rgb(255,255,255)'; - - - ctx.beginPath(); - var x = boxBody.position[0], - y = boxBody.position[1]; - ctx.save(); - ctx.translate(x, y); // Translate to the center of the box - ctx.rotate(boxBody.angle); // Rotate to the box body frame - ctx.rect(-boxShape.width/2, -boxShape.height/2, boxShape.width, boxShape.height); - ctx.stroke(); - ctx.closePath(); - // ctx.restore(); - - // ctx.save(); - // ctx.translate(game.width/2, game.height/2); // Translate to the center - // ctx.scale(50, -50); // Zoom in and flip y axis - - // ctx.lineWidth = 0.05; - // ctx.strokeStyle = 'rgb(255,255,255)'; - // ctx.beginPath(); - - // var y = planeBody.position[1]; - // ctx.rotate(0); // Rotate to the box body frame - // ctx.moveTo(-game.width, y); - // ctx.lineTo( game.width, y); - // ctx.stroke(); - - // ctx.closePath(); - ctx.restore(); -} - diff --git a/examples/wip/p23.js b/examples/wip/p23.js deleted file mode 100644 index 534d98889..000000000 --- a/examples/wip/p23.js +++ /dev/null @@ -1,59 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('box', 'assets/sprites/block.png'); - -} - -var box; -var move = false; -var start = 0; -var end = 0; - -function create() { - - box = game.add.sprite(200, 200, 'box'); - box.physicsEnabled = true; - - box.body.setZeroDamping(); - - game.input.onDown.addOnce(startTiming, this); - -} - -function startTiming() { - - start = game.time.now; - end = start + 1000; - move = true; - -} - -function update() { - - if (move) - { - box.body.moveLeft(100); - - if (game.time.now >= end) - { - move = false; - var duration = game.time.now - start; - console.log('Test over. Distance: ', box.x, 'duration', duration); - } - } - else - { - box.body.setZeroVelocity(); - } - -} - -function render() { - - game.debug.text('x: ' + box.body.velocity.x, 32, 32); - game.debug.text('y: ' + box.body.velocity.y, 32, 64); - -} diff --git a/examples/wip/p24.js b/examples/wip/p24.js deleted file mode 100644 index fa2adb292..000000000 --- a/examples/wip/p24.js +++ /dev/null @@ -1,127 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var box; -var box2; -var cursors; - -function p2px(v) { - return v *= -20; -} - -function px2p(v) { - return v * -0.05; -} - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.sprite(0, 0, 'backdrop'); - - box = game.add.sprite(200, 200, 'box'); - box.anchor.set(0.5); - box.physicsEnabled = true; - - box2 = game.add.sprite(400, 200, 'box'); - box2.anchor.set(0.5); // if using physics you nearly always need to anchor from the center like this unless you don't need rotation - // box2.scale.set(2); // if you need to scale, do it BEFORE enabling physics. You can't do it at run-time. - box2.physicsEnabled = true; - - box2.body.setZeroDamping(); - box2.body.fixedRotation = true; - - game.camera.follow(box2); - - cursors = game.input.keyboard.createCursorKeys(); - - game.physics.defaultRestitution = 0.8; - -} - -function update() { - - box2.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - box2.body.moveLeft(400); - } - else if (cursors.right.isDown) - { - box2.body.moveRight(400); - } - - if (cursors.up.isDown) - { - box2.body.moveUp(400); - } - else if (cursors.down.isDown) - { - box2.body.moveDown(400); - } - -} - -function render() { - - game.debug.text('x: ' + box2.body.velocity.x, 32, 32); - game.debug.text('y: ' + box2.body.velocity.y, 32, 64); - - // game.debug.text('x: ' + p2px(boxBody.position[0]), 32, 32); - // game.debug.text('y: ' + p2px(boxBody.position[1]), 32, 64); - // game.debug.text('r: ' + boxBody.angle, 32, 96); - - // drawbox(); - -} - -function drawbox() { - - // var ctx = game.context; - -/* - ctx.save(); - ctx.translate(game.width/2, game.height/2); // Translate to the center - ctx.scale(50, -50); // Zoom in and flip y axis - - ctx.lineWidth = 0.05; - ctx.strokeStyle = 'rgb(255,255,255)'; - - - ctx.beginPath(); - var x = boxBody.position[0], - y = boxBody.position[1]; - ctx.save(); - ctx.translate(x, y); // Translate to the center of the box - ctx.rotate(boxBody.angle); // Rotate to the box body frame - ctx.rect(-boxShape.width/2, -boxShape.height/2, boxShape.width, boxShape.height); - ctx.stroke(); - ctx.closePath(); - // ctx.restore(); -*/ - - // ctx.save(); - // ctx.translate(game.width/2, game.height/2); // Translate to the center - // ctx.scale(20, -20); // Zoom in and flip y axis - - // ctx.lineWidth = 0.05; - // ctx.strokeStyle = 'rgb(255,255,255)'; - // ctx.beginPath(); - - // var y = planeBody.position[1]; - // ctx.rotate(0); // Rotate to the box body frame - // ctx.moveTo(-game.width, y); - // ctx.lineTo( game.width, y); - // ctx.stroke(); - - // ctx.closePath(); - // ctx.restore(); -} - diff --git a/examples/wip/p25.js b/examples/wip/p25.js deleted file mode 100644 index b1a71b496..000000000 --- a/examples/wip/p25.js +++ /dev/null @@ -1,69 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('ship', 'assets/sprites/thrust_ship2.png'); - -} - -var ship; -var cursors; - -function p2px(v) { - return v *= -20; -} - -function px2p(v) { - return v * -0.05; -} - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - - var bg = game.add.sprite(0, 0, 'backdrop'); - bg.alpha = 0.2; - - ship = game.add.sprite(200, 200, 'ship'); - ship.anchor.set(0.5); - ship.physicsEnabled = true; - - game.camera.follow(ship); - - cursors = game.input.keyboard.createCursorKeys(); - - game.physics.defaultRestitution = 0.8; - -} - -function update() { - - if (cursors.left.isDown) - { - ship.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - ship.body.rotateRight(100); - } - else - { - ship.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - ship.body.thrust(400); - } - -} - -function render() { - - game.debug.text('x: ' + ship.body.x, 32, 32); - game.debug.text('y: ' + ship.body.y, 32, 64); - -} - diff --git a/examples/wip/p26.js b/examples/wip/p26.js deleted file mode 100644 index 02fd80110..000000000 --- a/examples/wip/p26.js +++ /dev/null @@ -1,85 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('box', 'assets/sprites/block.png'); - -} - -var box; -var move = false; -var start = 0; -var end = 0; - -function create() { - - box = game.add.sprite(200, 200, 'box'); - box.physicsEnabled = true; - - // Works - // box.body.setPolygon({}, [ [-1, 1], [-1, 0], [1, 0], [1, 1], [0.5, 0.5] ]); - - // Works - // box.body.setPolygon({}, [-1, 1], [-1, 0], [1, 0], [1, 1], [0.5, 0.5]); - - // Works - // box.body.setPolygon({}, -100, 100, -100, 0, 100, 0, 100, 100, 50, 50); - - // Works - box.body.setPolygon({}, -1, 1, -1, 0, 1, 0, 1, 1, 0.5, 0.5); - - - var path = [[-1, 1], - [-1, 0], - [1, 0], - [1, 1], - [0.5, 0.5]]; - - // box.body.data.fromPolygon(path); - -console.log('real path'); -console.log(path); - - - - // box.body.setZeroDamping(); - - // game.input.onDown.addOnce(startTiming, this); - -} - -function startTiming() { - - start = game.time.now; - end = start + 1000; - move = true; - -} - -function update() { - - if (move) - { - box.body.moveLeft(100); - - if (game.time.now >= end) - { - move = false; - var duration = game.time.now - start; - console.log('Test over. Distance: ', box.x, 'duration', duration); - } - } - else - { - box.body.setZeroVelocity(); - } - -} - -function render() { - - game.debug.text('x: ' + box.body.velocity.x, 32, 32); - game.debug.text('y: ' + box.body.velocity.y, 32, 64); - -} diff --git a/examples/wip/p27.js b/examples/wip/p27.js deleted file mode 100644 index f3524d913..000000000 --- a/examples/wip/p27.js +++ /dev/null @@ -1,98 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('box', 'assets/sprites/diamond.png'); - game.load.physics('physobjects', 'assets/physics/diamond.json'); - -} - -var box; -var bmd; -var move = false; -var start = 0; -var end = 0; - -function create() { - - bmd = game.add.bitmapData(800, 600); - game.add.image(0, 0, bmd); - - box = game.add.sprite(300, 300, 'box'); - // box.anchor.set(0.5); - - box.physicsEnabled = true; - - box.body.clearShapes(); - - box.body.loadPolygon('physobjects', 'diamond'); - - box.body.rotateLeft(20); - - // console.log(game.cache.getPhysicsData('physobjects', 'diamond')); - - // 95x95 - // box.body.setRectangle(64, 64); - - // box.body.setRectangle(64, 64, 95/2,95/2); - - // Works - // box.body.clearShapes(); - // box.body.addPolygon({}, [ [-1, 1], [-1, 0], [1, 0], [1, 1], [0.5, 0.5] ]); - - // Works - // box.body.setPolygon({}, [-1, 1], [-1, 0], [1, 0], [1, 1], [0.5, 0.5]); - - // Works - // box.body.addPolygon({}, -100, 100, -100, 0, 100, 0, 100, 100, 50, 50); - - // box.body.addPolygon({}, -100, 100, -100, 0, 100, 0, 100, 100, 50, 50 ); - - // box.body.addPolygon({}, 32, 13 , 17, 28 , 15, 28 , 0, 13 , 0, 7 , 7, 0 , 25, 0 , 32, 7 ); - - // Works - // box.body.setPolygon({}, -1, 1, -1, 0, 1, 0, 1, 1, 0.5, 0.5); - - // box.body.setZeroDamping(); - - // game.input.onDown.addOnce(startTiming, this); - -} - -function startTiming() { - - start = game.time.now; - end = start + 1000; - move = true; - -} - -function update() { - - if (move) - { - box.body.moveLeft(100); - - // if (game.time.now >= end) - // { - // move = false; - // var duration = game.time.now - start; - // console.log('Test over. Distance: ', box.x, 'duration', duration); - // } - } - else - { - // box.body.setZeroVelocity(); - } - -} - -function render() { - - game.debug.physicsBody(box.body, 0); - - // game.debug.text(box.body., 32, 32); - // game.debug.text('y: ' + box.body.velocity.y, 32, 64); - -} diff --git a/examples/wip/p28.js b/examples/wip/p28.js deleted file mode 100644 index 60046f593..000000000 --- a/examples/wip/p28.js +++ /dev/null @@ -1,70 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var box; -var box2; -var cursors; - -function create() { - - // If you're going to resize the world, it's easier to do it BEFORE enabling P2 - game.world.setBounds(0, 0, 1920, 1200); - - // Enable p2 physics - game.physics.startSystem(Phaser.Physics.P2JS); - game.physics.p2.defaultRestitution = 0.8; - - game.add.sprite(0, 0, 'backdrop'); - - box = game.add.sprite(200, 200, 'box'); - box.name = 'bob'; - - box2 = game.add.sprite(400, 200, 'box'); - box2.name = 'ben'; - - game.physics.p2.enable([box, box2]); - - box2.body.setZeroDamping(); - box2.body.fixedRotation = true; - - game.camera.follow(box2); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - box2.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - box2.body.moveLeft(400); - } - else if (cursors.right.isDown) - { - box2.body.moveRight(400); - } - - if (cursors.up.isDown) - { - box2.body.moveUp(400); - } - else if (cursors.down.isDown) - { - box2.body.moveDown(400); - } - -} - -function render() { - -} - diff --git a/examples/wip/particle1.js b/examples/wip/particle1.js deleted file mode 100644 index 2a34adb21..000000000 --- a/examples/wip/particle1.js +++ /dev/null @@ -1,78 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('ship', 'assets/sprites/thrust_ship2.png'); - game.load.image('chunk', 'assets/sprites/chunk.png'); - -} - -var ship; -var sprite2; -var body; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - game.physics.gravity[1] = -1; - - ship = game.add.sprite(200, 200, 'ship'); - ship.physicsEnabled = true; - // We do this because our ship is shaped like a triangle, not a square :) - ship.body.addPolygon({}, 29, 23 , 0, 23 , 14, 1); - - sprite2 = game.add.sprite(300, 300, 'chunk'); - - cursors = game.input.keyboard.createCursorKeys(); - - game.input.onDown.add(spawn, this); - -} - -function spawn() { - - body = new Phaser.Physics.Body(game, null, 300, 100, 1); - - body.addParticle(4, 4, 0, 0, 0); - - game.physics.addBody(body.data); - -} - -function update() { - - if (body) - { - sprite2.x = body.x; - sprite2.y = body.y; - } - - if (cursors.left.isDown) - { - ship.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - ship.body.rotateRight(100); - } - else - { - ship.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - ship.body.thrust(400); - } - else if (cursors.down.isDown) - { - ship.body.reverse(400); - } - -} - -function render() { - -} diff --git a/examples/wip/pausetime.js b/examples/wip/pausetime.js deleted file mode 100644 index 9a0f25dc3..000000000 --- a/examples/wip/pausetime.js +++ /dev/null @@ -1,57 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create, render: render }); - -var log = ''; -var t; - -function create() { - - log += 'game started at ' + this.time.now + '\n'; - // log += 'pagehide? ' + window['onpagehide'] + '\n'; - // log += 'blur? ' + window['blur'] + '\n'; - - console.log('game started at ' + this.time.now); - - game.stage.backgroundColor = '#2d2d2d'; - - game.onPause.add(onGamePause, this); - game.onResume.add(onGameResume, this); - - t = game.add.text(32, 32, log, { font: '14px Arial', fill: '#ffffff' }); - - // window.unload = function() { console.log('unload'); }; - -} - -function onGamePause(event) { - - log += 'game paused at ' + this.time.now + '\n'; - log += 'event ' + event.type + '\n'; - - console.log('game paused at ' + this.time.now); - -} - -function onGameResume(event) { - - log += 'game un-paused at ' + this.time.now + '\n'; - log += 'was paused for ' + game.time.pauseDuration + '\n'; - log += 'event ' + event.type + '\n'; - - console.log('game un-paused at ' + this.time.now); - console.log('was paused for ' + game.time.pauseDuration); - -} - -function render() { - - // console.log('tick'); - - t.text = log; - - game.debug.text('now: ' + game.time.now, 500, 32); - - // game.debug.text(log, 32, 64); - // game.debug.text('paused: ' + game.paused, 32, 64); - -} diff --git a/examples/wip/physics config.js b/examples/wip/physics config.js deleted file mode 100644 index 444528029..000000000 --- a/examples/wip/physics config.js +++ /dev/null @@ -1,108 +0,0 @@ -// Here we'll use a Physics Configuration object to specify which physics systems should be started with the game. - -var physicsConfig = { - - arcade: true, - ninja: false, - p2: true - -}; - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }, false, false, physicsConfig); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - game.load.spritesheet('bullets', 'assets/sprites/balls.png', 17, 17); - -} - -var atari; -var balls; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - balls = game.add.group(); - - balls.createMultiple(250, 'bullets', 0, false); - - atari = game.add.sprite(300, 450, 'atari'); - - game.physics.arcade.gravity.y = 400; - - // Enable physics on everything added to the world so far (the true parameter makes it recurse down into children) - game.physics.arcade.enable(game.world, true); - - atari.body.gravityScale.y = 0; - atari.body.immovable = true; - - cursors = game.input.keyboard.createCursorKeys(); - - game.time.events.loop(150, fire, this); - -} - -function fire() { - - var ball = balls.getFirstExists(false); - - if (ball) - { - ball.frame = game.rnd.integerInRange(0,6); - ball.exists = true; - ball.reset(game.world.randomX, 0); - - ball.body.bounce.y = 0.8; - } - -} - -function reflect(a, ball) { - - if (ball.y > (atari.y + 5)) - { - return true; - } - else - { - ball.body.velocity.x = atari.body.velocity.x; - ball.body.velocity.y *= -(ball.body.bounce.y); - - return false; - } - -} - -function update() { - - game.physics.arcade.collide(atari, balls, null, reflect, this); - - atari.body.velocity.x = 0; - - if (cursors.left.isDown) - { - atari.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - atari.body.velocity.x = 200; - } - - balls.forEachAlive(checkBounds, this); - -} - -function checkBounds(ball) { - - if (ball.y > 600) - { - ball.kill(); - } - -} - -function render() { - -} diff --git a/examples/wip/physics-1.js b/examples/wip/physics-1.js deleted file mode 100644 index dc6882191..000000000 --- a/examples/wip/physics-1.js +++ /dev/null @@ -1,63 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('atari', 'assets/sprites/atari130xe.png'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -var sprite1; -var sprite2; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - // This will check Sprite vs. Sprite collision - - sprite1 = game.add.sprite(50, 200, 'atari'); - sprite1.name = 'atari'; - // sprite1.anchor.set(0.5); - - sprite2 = game.add.sprite(700, 220, 'mushroom'); - sprite2.name = 'mushroom'; - - // Enable the physics bodies of both sprites - game.physics.enable([sprite1, sprite2]); - - // And move 'em - sprite1.body.velocity.x = 100; - sprite2.body.velocity.x = -100; - -} - -function update() { - - // object1, object2, collideCallback, processCallback, callbackContext - game.physics.arcade.collide(sprite1, sprite2, collisionHandler, null, this); - - // var b = sprite1.getBounds(); - // console.log(b); - -} - -function collisionHandler (obj1, obj2) { - - // The two sprites are colliding - game.stage.backgroundColor = '#992d2d'; - -} - - -function render() { - - // var b = sprite1.getBounds(); - - // game.debug.geom(b, 'rgba(255,0,0,0.8)', true, 1); - - game.debug.geom(sprite1.body, 'rgba(0,255,0,0.4)', true, 1); - game.debug.geom(sprite2.body, 'rgba(0,255,0,0.4)', true, 1); - -} \ No newline at end of file diff --git a/examples/wip/physics-2.js b/examples/wip/physics-2.js deleted file mode 100644 index def380316..000000000 --- a/examples/wip/physics-2.js +++ /dev/null @@ -1,107 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/tile_collision_test.json', null, Phaser.Tilemap.TILED_JSON); - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('phaser', 'assets/sprites/arrow.png'); - game.load.spritesheet('coin', 'assets/sprites/coin.png', 32, 32); - -} - -var map; -var layer; - -var sprite; -var cursors; - -function create() { - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - // map.addTilesetImage('coin'); - - map.setCollisionBetween(1, 12); - - // map.setTileIndexCallback(26, hitCoin, this); - - // map.setTileLocationCallback(2, 0, 1, 1, hitCoin, this); - - layer = map.createLayer('Tile Layer 1'); - - layer.debug = true; - - layer.resizeWorld(); - - // game.physics.arcade.gravity.y = 100; - - sprite = game.add.sprite(260, 100, 'phaser'); - sprite.anchor.setTo(0.5, 0.5); - - game.physics.enable(sprite); - - // sprite.body.setRectangle(16, 16, 8, 8); - - // We'll set a lower max angular velocity here to keep it from going totally nuts - sprite.body.maxAngular = 500; - - // Apply a drag otherwise the sprite will just spin and never slow down - sprite.body.angularDrag = 50; - - // sprite.body.bounce.x = 0.8; - // sprite.body.bounce.y = 0.8; - - debugSprite = sprite; - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function hitCoin(sprite, tile) { - - tile.tile.alpha = 0.2; - - layer.dirty = true; - - return false; - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - sprite.body.angularVelocity = 0; - - if (cursors.left.isDown) - { - sprite.body.angularVelocity = -300; - } - else if (cursors.right.isDown) - { - sprite.body.angularVelocity = 300; - } - - if (cursors.up.isDown) - { - game.physics.arcade.velocityFromAngle(sprite.angle, 300, sprite.body.velocity); - } - -} - -function render() { - - // game.debug.bodyInfo(sprite, 16, 24); - // game.debug.physicsBody(sprite.body); - - var r = new Phaser.Rectangle(sprite.body.x, sprite.body.y, sprite.body.width, sprite.body.height); - game.debug.geom(r); - -} \ No newline at end of file diff --git a/examples/wip/pixi1.js b/examples/wip/pixi1.js deleted file mode 100644 index 4771b35b0..000000000 --- a/examples/wip/pixi1.js +++ /dev/null @@ -1,54 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }, false); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var sprite; -var sprite2; -var g; -var p; - -function create() { - - game.stage.backgroundColor = '#ff5500'; - - sprite = game.add.sprite(0, -200, 'pic'); - - // g = game.add.group(null, 'billy'); - - // sprite2 = g.create(0, 0, 'pic'); - - // g.y = 200; - // g.rotation = 0.1; - - sprite2 = game.add.sprite(0, 300, 'pic'); - - // game.input.onDown.add(tint, this); - - game.add.tween(sprite).to({y: 500}, 3000, Phaser.Easing.Linear.None, true); - - p = new PIXI.Point(43, 45); - -} - -function tint() { - - // sprite.tint = Math.random() * 0xFFFFFF; - // sprite2.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - -} - -function render() { - - // game.debug.text(sprite.position.y, 32, 32); - -} diff --git a/examples/wip/pixi2.js b/examples/wip/pixi2.js deleted file mode 100644 index d455a9dab..000000000 --- a/examples/wip/pixi2.js +++ /dev/null @@ -1,88 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('beast', 'assets/pics/shadow_of_the_beast2_karamoon.png'); - game.load.image('snot', 'assets/pics/nslide_snot.png'); - game.load.image('atari1', 'assets/sprites/atari130xe.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - game.load.image('coke', 'assets/sprites/cokecan.png'); - game.load.image('disk', 'assets/sprites/oz_pov_melting_disk.png'); - -} - -var group1; -var group2; -var coke; -var disk; - -function create() { - - // Create a background image - game.add.sprite(0, 0, 'beast'); - - // Create a Group that will sit above the background image - group1 = game.add.group(); - - // Create a Group that will sit above Group 1 - group2 = game.add.group(); - - // Now let's create some random sprites and enable them all for drag and 'bring to top' - for (var i = 0; i < 10; i++) - { - var tempSprite = game.add.sprite(game.world.randomX, game.world.randomY, 'atari1'); - - tempSprite.name = 'atari' + i; - tempSprite.input.start(i, true); - tempSprite.input.enableDrag(false, true); - - group1.add(tempSprite); - - // Sonics - - var tempSprite=game.add.sprite(game.world.randomX, game.world.randomY, 'sonic'); - - tempSprite.name = 'sonic' + i; - tempSprite.input.start(10 + i, true); - tempSprite.input.enableDrag(false, true); - - group2.add(tempSprite); - } - - // Add 2 control sprites into each group - these cannot be dragged but should be bought to the top each time - coke = group1.create(100, 100, 'coke'); - disk = group2.create(400, 300, 'disk'); - - // Create a foreground image - everything should appear behind this, even when dragged - var snot = game.add.sprite(game.world.centerX, game.world.height, 'snot'); - snot.anchor.setTo(0.5, 1); - - // You can click and drag any sprite but Sonic sprites should always appear above the Atari sprites - // and both types of sprite should only ever appear above the background and behind the - - game.input.onDown.add(wibble, this); - -} - -function wibble(p) { - console.log(p); -} - -function update() { - - if (game.input.keyboard.justReleased(Phaser.Keyboard.ONE)) - { - coke.bringToTop(); - } - - if (game.input.keyboard.justReleased(Phaser.Keyboard.TWO)) - { - disk.bringToTop(); - } - -} - -function render() { - game.debug.inputInfo(32, 32); -} diff --git a/examples/wip/platforms.js b/examples/wip/platforms.js deleted file mode 100644 index e7d4410dd..000000000 --- a/examples/wip/platforms.js +++ /dev/null @@ -1,158 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('dude', 'assets/games/starstruck/dude.png', 32, 48); - game.load.image('background', 'assets/games/starstruck/background2.png'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var player; -var facing = 'left'; -var jumpTimer = 0; -var cursors; -var jumpButton; - -var boxes; - -function create() { - - game.stage.backgroundColor = '#000000'; - - bg = game.add.tileSprite(0, 0, 800, 600, 'background'); - bg.fixedToCamera = true; - - game.physics.gravity.y = 20.0; - - game.world.setBounds(0, 0, 2000, 600); - - game.physics.setBoundsToWorld(true, true, false, true, false); - - game.physics.friction = 0.5; - game.physics.enableBodySleeping = true; - game.physics.world.solver.stiffness = 1e20; - game.physics.world.solver.relaxation = 3; - - // Materials - var groundMaterial = game.physics.createMaterial('ground'); - var characterMaterial = game.physics.createMaterial('character'); - var boxMaterial = game.physics.createMaterial('box'); - - player = game.add.sprite(100, -400, 'dude'); - player.physicsEnabled = true; - player.body.fixedRotation = true; - player.body.setMaterial(characterMaterial); - player.body.mass = 1; - player.body.damping = 0.5; - - player.animations.add('left', [0, 1, 2, 3], 10, true); - player.animations.add('turn', [4], 20, true); - player.animations.add('right', [5, 6, 7, 8], 10, true); - - boxes = game.add.group(); - - for (var i = 0; i < 100; i++) - { - var box = boxes.create(game.rnd.integerInRange(200, 1700), game.rnd.integerInRange(-200, 400), 'box'); - box.scale.set(game.rnd.realInRange(0.2, 0.6)); - box.physicsEnabled = true; - box.body.allowSleep = true; - box.body.mass = 10; - box.body.setMaterial(boxMaterial); - box.body.fixedRotation = true; - } - - // Set the material along the ground - game.physics.setWorldMaterial(groundMaterial); - - var groundCharacterCM = game.physics.createContactMaterial(groundMaterial, characterMaterial, { friction: 0.0 }); // no friction between character and ground - var boxCharacterCM = game.physics.createContactMaterial(boxMaterial, characterMaterial, { friction: 0.0 }); // No friction between character and boxes - var boxGroundCM = game.physics.createContactMaterial(boxMaterial, groundMaterial, { friction: 0.6 }); // Between boxes and ground - - game.camera.follow(player); - - cursors = game.input.keyboard.createCursorKeys(); - jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); - -} - -function update() { - - bg.tilePosition.x = -game.camera.view.x; - - if (cursors.left.isDown) - { - player.body.moveLeft(200); - - if (facing != 'left') - { - player.animations.play('left'); - facing = 'left'; - } - } - else if (cursors.right.isDown) - { - player.body.moveRight(200); - - if (facing != 'right') - { - player.animations.play('right'); - facing = 'right'; - } - } - else - { - player.body.velocity.x = 0; - - if (facing != 'idle') - { - player.animations.stop(); - - if (facing == 'left') - { - player.frame = 0; - } - else - { - player.frame = 5; - } - - facing = 'idle'; - } - } - - if (jumpButton.isDown && game.time.now > jumpTimer && checkIfCanJump()) - { - player.body.moveUp(300); - jumpTimer = game.time.now + 750; - } - -} - -function checkIfCanJump(){ -var yAxis = p2.vec2.fromValues(0,1); -var result = false; -for(var i=0; i 0.5) result = true; - } -} -return result; -} - - -function render () { - - // if (player.debug) - // { - game.debug.physicsBody(player.body); - // game.debug.bodyInfo(player, 16, 24); - // } - -} diff --git a/examples/wip/priority.js b/examples/wip/priority.js deleted file mode 100644 index 7780cea7c..000000000 --- a/examples/wip/priority.js +++ /dev/null @@ -1,42 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var sprite1; -var sprite2; -var sprite3; - -function create() { - - sprite1 = game.add.sprite(200, 300, 'seacreatures', 'blueJellyfish0000'); - sprite2 = game.add.sprite(230, 300, 'seacreatures', 'crab10000'); - sprite3 = game.add.sprite(280, 250, 'seacreatures', 'seahorse0000'); - - sprite1.inputEnabled = true; - sprite2.inputEnabled = true; - sprite3.inputEnabled = true; - - sprite1.input.priorityID = 0; - sprite2.input.priorityID = 1; - sprite3.input.priorityID = 2; - - sprite1.input.pixelPerfectClick = true; - sprite2.input.pixelPerfectClick = true; - sprite3.input.pixelPerfectClick = true; - - sprite1.events.onInputDown.add(clicked, this); - sprite2.events.onInputDown.add(clicked, this); - sprite3.events.onInputDown.add(clicked, this); - -} - -function clicked(s) { - - console.log('clicked', s.frameName); - -} diff --git a/examples/wip/rendertexture.js b/examples/wip/rendertexture.js deleted file mode 100644 index 7324c90a0..000000000 --- a/examples/wip/rendertexture.js +++ /dev/null @@ -1,48 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.WEBGL, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - -} - -var mushroom; -var texture; -var image; - -function create() { - - texture = game.add.renderTexture('mousetrail', 800, 600); - - // We create a sprite (rather than using the factory) so it doesn't get added to the display, as we only need its texture data. - mushroom = new Phaser.Sprite(game, 0, 0, 'mushroom'); - mushroom.anchor.setTo(0.5, 0.5); - - // This is the sprite that is drawn to the display. We've given it the renderTexture as its texture. - image = game.add.image(0, 0, texture); - - game.input.onDown.add(tint, this); - -} - -function tint() { - - image.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - - if (!game.input.activePointer.position.isZero()) - { - // Here we draw the mushroom sprite to the renderTexture at the pointer coordinates. - // The 'false' parameter 2nd from the end tells it not to clear itself, causing the trail effect you see. - texture.render(mushroom, game.input.activePointer.position, false); - } - -} - -function render() { - -} diff --git a/examples/wip/retro font effect.js b/examples/wip/retro font effect.js deleted file mode 100644 index d96a2d9b4..000000000 --- a/examples/wip/retro font effect.js +++ /dev/null @@ -1,112 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('knightHawks', 'assets/fonts/retroFonts/KNIGHT3.png'); - -} - -var font; -var images; -var dataV; -var dataH; -var dataH2; -var sine = 0; -var total = 24; -var posV = []; -var posH = []; -var text = [ 'phaser v2', 'this march', 'yay retro fonts!', 'shaders', 'filters', 'blend modes', 'full body physics', 'and cats', '(maybe not cats)', '------------' ]; -var textIndex = 0; - -function create() { - - game.stage.smoothed = true; - - font = game.add.retroFont('knightHawks', 31, 25, Phaser.RetroFont.TEXT_SET6, 10, 1, 1); - font.text = 'phaser v2'; - - // Let's create 2 sets of generated tween data - one going vertically, one going horizontally, at different speeds - var tweenData = { x: 200, y: 64 }; - - tween = game.make.tween(tweenData).to( { y: 500 }, 2000, Phaser.Easing.Sinusoidal.InOut); - tween.yoyo(true); - tween.interpolation(game.math.catmullRomInterpolation); - dataV = tween.generateData(60); - - tween = game.make.tween(tweenData).to( { x: 600 }, 1500, Phaser.Easing.Sinusoidal.InOut); - tween.yoyo(true); - tween.interpolation(game.math.catmullRomInterpolation); - dataH = tween.generateData(60); - - tween = game.make.tween(tweenData).to( { x: 600 }, 1500, Phaser.Easing.Elastic.InOut); - tween.yoyo(true); - tween.interpolation(game.math.catmullRomInterpolation); - dataH2 = tween.generateData(60); - - images = game.add.group(); - - var tmp; - - for (var i = 0; i < total; i++) - { - tmp = images.create(game.world.centerX, 64, font); - tmp.anchor.set(0.5); - tmp.scale.set(2); - // tmp.alpha = (1.0 / total) * i; - posV.push(i * 4); - posH.push(i); - } - - images.reverse(); - - game.time.events.loop(4000, updateText, this); - game.time.events.loop(6000, updateSine, this); - -} - -function updateSine() { - - sine++; - - if (sine === 2) - { - sine = 0; - } - -} - -function updateText() { - - textIndex = game.math.wrapValue(textIndex, 1, text.length); - - font.text = text[textIndex]; - -} - -function update() { - - var pv, ph; - - for (var i = 0; i < total; i++) - { - pv = posV[i]; - ph = posH[i]; - - if (sine === 0) - { - images.getAt(i).x = dataH[ph].x; - } - else - { - images.getAt(i).x = dataH2[ph].x; - } - - images.getAt(i).y = dataV[pv].y; - - posV[i] = game.math.wrapValue(pv, 1, dataV.length); - posH[i] = game.math.wrapValue(ph, 1, dataH.length); - - } - -} diff --git a/examples/wip/rnd.js b/examples/wip/rnd.js deleted file mode 100644 index 9e9c0362e..000000000 --- a/examples/wip/rnd.js +++ /dev/null @@ -1,40 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - -} - -var sprite; - -function create() { - - for (var i = 0; i < 1000; i++) - { - var x = game.rnd.integerInRange(10, 20); - - if (x === 20) - { - console.log('>>>', x); - } - else if (x === 10) - { - console.log('---', x); - } - else - { - // console.log(x); - } - } - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/sci-fly2.js b/examples/wip/sci-fly2.js deleted file mode 100644 index c7e8772dc..000000000 --- a/examples/wip/sci-fly2.js +++ /dev/null @@ -1,107 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('level3', 'assets/tilemaps/maps/cybernoid.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tiles', 'assets/tilemaps/tiles/cybernoid.png', 16, 16); - game.load.image('phaser', 'assets/sprites/phaser-ship.png'); - game.load.image('chunk', 'assets/sprites/chunk.png'); - -} - -var map; -var layer; -var cursors; -var sprite; -var emitter; - -function create() { - - // A Tilemap object just holds the data needed to describe the map (i.e. the json exported from Tiled, or the CSV exported from elsewhere). - // You can add your own data or manipulate the data (swap tiles around, etc) but in order to display it you need to create a TilemapLayer. - map = game.add.tilemap('level3'); - - map.addTilesetImage('CybernoidMap3BG_bank.png', 'tiles'); - - layer = map.createLayer(0); - - // Basically this sets EVERY SINGLE tile to fully collide on all faces - map.setCollisionByExclusion([7, 32, 35, 36, 47]); - - // layer.debug = true; - - layer.resizeWorld(); - - cursors = game.input.keyboard.createCursorKeys(); - - emitter = game.add.emitter(0, 0, 200); - - emitter.makeParticles('chunk'); - emitter.minRotation = 0; - emitter.maxRotation = 0; - emitter.gravity = 150; - emitter.bounce.setTo(0.5, 0.5); - - sprite = game.add.sprite(200, 70, 'phaser'); - sprite.anchor.set(0.5); - - game.physics.enable(sprite); - - // Because both our body and our tiles are so tiny, - // and the body is moving pretty fast, we need to add - // some tile padding to the body. WHat this does - sprite.body.tilePadding.set(64, 64); - - game.camera.follow(sprite); - -} - -function particleBurst() { - - emitter.x = sprite.x; - emitter.y = sprite.y; - emitter.start(true, 2000, null, 1); - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - game.physics.arcade.collide(emitter, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - particleBurst(); - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - particleBurst(); - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - sprite.scale.x = -1; - particleBurst(); - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - sprite.scale.x = 1; - particleBurst(); - } - -} - -function render() { - - game.debug.body(sprite); - -} diff --git a/examples/wip/springs 1.js b/examples/wip/springs 1.js deleted file mode 100644 index f422f178a..000000000 --- a/examples/wip/springs 1.js +++ /dev/null @@ -1,92 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('box', 'assets/sprites/block.png'); - -} - -var box1; -var box2; -var s; - -var cursors; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.sprite(0, 0, 'backdrop'); - -// game.physics.gravity.y = -9.78; - game.physics.gravity[1] = -9.78; - - // game.physics.onBodyAdded.add(addedToWorld, this); - - box1 = game.add.sprite(200, 200, 'box'); - box1.physicsEnabled = true; - // box1.body.fixedRotation = true; - // box1.body.mass = 3; - - box2 = game.add.sprite(400, 200, 'box'); - box2.physicsEnabled = true; - // box2.body.fixedRotation = true; - - s = new Phaser.Physics.Spring(game, box1.body.data, box2.body.data, 2, 10, 1, null, null, [ 0, 70 ], [ 0, 70 ]); - - game.physics.addSpring(s); - - // var s = new p2.Spring(box1, box2, { - // restLength : 1, - // stiffness : 10, - // localAnchorA : [0,0.5], - // localAnchorB : [0,0.5], - // }); - // world.addSpring(s); - - game.camera.follow(box2); - - cursors = game.input.keyboard.createCursorKeys(); - - // game.physics.defaultRestitution = 0.8; - -} - -function addedToWorld(body, world) { - - console.log('Body added for', body); - -} - -function update() { - - box2.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - box2.body.moveLeft(400); - } - else if (cursors.right.isDown) - { - box2.body.moveRight(400); - } - - if (cursors.up.isDown) - { - box2.body.moveUp(400); - } - else if (cursors.down.isDown) - { - box2.body.moveDown(400); - } - -} - -function render() { - - // game.debug.text('x: ' + box2.body.velocity.x, 32, 32); - // game.debug.text('y: ' + box2.body.velocity.y, 32, 64); - -} - diff --git a/examples/wip/spritebatch1.js b/examples/wip/spritebatch1.js deleted file mode 100644 index 51f8033d1..000000000 --- a/examples/wip/spritebatch1.js +++ /dev/null @@ -1,62 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('maggot', 'assets/sprites/ilkke.png'); - -} - -var batch; -var dudeBoundsPadding = 100; -var dudeBounds = new Phaser.Rectangle(-dudeBoundsPadding, -dudeBoundsPadding, 800 + dudeBoundsPadding * 2, 600 + dudeBoundsPadding * 2); -var tick = 0; - -function create() { - - batch = game.add.spriteBatch(); - - var total = (game.renderType === Phaser.WEBGL) ? 1500 : 100; - - for (var i = 0; i < total; i++) - { - var dude = batch.create(game.world.randomX, game.world.randomY, 'maggot'); - - dude.anchor.set(0.5); - dude.scale.set(0.8 + Math.random() * 0.3); - dude.direction = Math.random() * Math.PI * 2; - dude.turningSpeed = Math.random() - 0.8; - dude.speed = (2 + Math.random() * 2) * 0.2; - dude.offset = Math.random() * 100; - } - -} - -function update() { - - batch.forEach(updateMaggot, this, false); - - tick += 0.1; - -} - -function updateMaggot(dude) { - - dude.scale.y = 0.95 + Math.sin(tick + dude.offset) * 0.15 - dude.direction += dude.turningSpeed * 0.02; - dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); - dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); - dude.rotation = -dude.direction + Math.PI; - - // wrap the dudes by testing their bounds.. - if (dude.position.x < dudeBounds.x) - dude.position.x += dudeBounds.width; - else if (dude.position.x > dudeBounds.x + dudeBounds.width) - dude.position.x -= dudeBounds.width; - - if (dude.position.y < dudeBounds.y) - dude.position.y += dudeBounds.height; - else if (dude.position.y > dudeBounds.y + dudeBounds.height) - dude.position.y -= dudeBounds.height; - -} diff --git a/examples/wip/spritebatch2.js b/examples/wip/spritebatch2.js deleted file mode 100644 index d7f3436d4..000000000 --- a/examples/wip/spritebatch2.js +++ /dev/null @@ -1,69 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('knightHawks', 'assets/fonts/KNIGHT3.png'); - game.load.image('maggot', 'assets/sprites/ilkke.png'); - -} - -var font; -var batch; -var dudeBoundsPadding = 100; -var dudeBounds = new Phaser.Rectangle(-dudeBoundsPadding, -dudeBoundsPadding, 800 + dudeBoundsPadding * 2, 600 + dudeBoundsPadding * 2); -var tick = 0; - -function create() { - - font = game.add.bitmapFont(0, 0, 'knightHawks', 31, 25, Phaser.BitmapFont.TEXT_SET6, 10, 1, 1); - font.text = 'phaser'; - - batch = game.add.spriteBatch(); - - var total = (game.renderType === Phaser.WEBGL) ? 1500 : 100; - - console.log(font.width, font.height, font.bmd.width, font.bmd.height); - - for (var i = 0; i < total; i++) - { - var dude = batch.create(game.world.randomX, game.world.randomY, font.bmd); - - dude.anchor.set(0.5); - // dude.scale.set(0.8 + Math.random() * 0.3); - dude.direction = Math.random() * Math.PI * 2; - dude.turningSpeed = Math.random() - 0.8; - dude.speed = (2 + Math.random() * 2) * 0.2; - dude.offset = Math.random() * 100; - } - -} - -function update() { - - batch.forEach(updateMaggot, this, false); - - tick += 0.1; - -} - -function updateMaggot(dude) { - - // dude.scale.y = 0.95 + Math.sin(tick + dude.offset) * 0.15 - dude.direction += dude.turningSpeed * 0.02; - dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); - dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); - dude.rotation = -dude.direction + Math.PI; - - // wrap the dudes by testing their bounds.. - if (dude.position.x < dudeBounds.x) - dude.position.x += dudeBounds.width; - else if (dude.position.x > dudeBounds.x + dudeBounds.width) - dude.position.x -= dudeBounds.width; - - if (dude.position.y < dudeBounds.y) - dude.position.y += dudeBounds.height; - else if (dude.position.y > dudeBounds.y + dudeBounds.height) - dude.position.y -= dudeBounds.height; - -} diff --git a/examples/wip/state parameters.js b/examples/wip/state parameters.js deleted file mode 100644 index 2f2e402e5..000000000 --- a/examples/wip/state parameters.js +++ /dev/null @@ -1,94 +0,0 @@ -var BasicGame = {}; - -BasicGame.Boot = function (game) { - - this.a; - this.b; - -}; - -BasicGame.Boot.prototype = { - - init: function (a, b) { - - this.a = a; - this.b = b; - console.log('Boot is alive'); - console.log('A: ', this.a); - console.log('B: ', this.b); - - }, - - create: function () { - - console.log('Boot create'); - this.game.state.start('Preloader', true, false, this.a, this.b); - - } - -}; - -BasicGame.Preloader = function (game) { - - this.a; - this.b; - -}; - -BasicGame.Preloader.prototype = { - - init: function (a, b) { - - this.a = a; - this.b = b; - console.log('Preloader is alive'); - console.log('A: ', this.a); - console.log('B: ', this.b); - - }, - - create: function () { - - console.log('Preloader create'); - this.game.state.start('MainMenu', true, false, this.a, this.b); - - } - -}; - -BasicGame.MainMenu = function (game) { - - this.a; - this.b; - -}; - -BasicGame.MainMenu.prototype = { - - init: function (a, b) { - - this.a = a; - this.b = b; - - }, - - create: function () { - - this.game.stage.backgroundColor = 0x2d2d2d; - - console.log('Main Menu is alive'); - console.log('A: ', this.a); - console.log('B: ', this.b); - console.log(this.game); - - } - -}; - -var game = new Phaser.Game(1024, 768, Phaser.AUTO, 'phaser-example'); - -game.state.add('Boot', BasicGame.Boot); -game.state.add('Preloader', BasicGame.Preloader); -game.state.add('MainMenu', BasicGame.MainMenu); - -game.state.start('Boot', true, false, 'hello', 'world'); diff --git a/examples/wip/state smoothed.js b/examples/wip/state smoothed.js deleted file mode 100644 index 193a19178..000000000 --- a/examples/wip/state smoothed.js +++ /dev/null @@ -1,105 +0,0 @@ -var BasicGame = {}; - -BasicGame.Boot = function (game) { - - this.a; - this.b; - -}; - -BasicGame.Boot.prototype = { - - init: function (a, b) { - - this.a = a; - this.b = b; - console.log('Boot is alive'); - console.log('A: ', this.a); - console.log('B: ', this.b); - - }, - - create: function () { - - this.stage.smoothed = false; - console.log('Boot create'); - this.game.state.start('Preloader', true, false, this.a, this.b); - - } - -}; - -BasicGame.Preloader = function (game) { - - this.a; - this.b; - -}; - -BasicGame.Preloader.prototype = { - - init: function (a, b) { - - this.a = a; - this.b = b; - console.log('Preloader is alive'); - console.log('A: ', this.a); - console.log('B: ', this.b); - - }, - - preload: function () { - - this.load.image('backdrop', 'assets/pics/atari_fujilogo.png'); - - }, - - create: function () { - - console.log('Preloader create'); - this.game.state.start('MainMenu', true, false, this.a, this.b); - - } - -}; - -BasicGame.MainMenu = function (game) { - - this.a; - this.b; - -}; - -BasicGame.MainMenu.prototype = { - - init: function (a, b) { - - this.a = a; - this.b = b; - - }, - - create: function () { - - this.game.stage.backgroundColor = 0x2d2d2d; - - console.log('Main Menu is alive'); - console.log('A: ', this.a); - console.log('B: ', this.b); - console.log(this.stage.smoothed); - - var s = this.add.sprite(0, 0, 'backdrop'); - s.scale.set(4); - - } - -}; - -// var game = new Phaser.Game(1024, 768, Phaser.AUTO, 'phaser-example', null, false, false); -var game = new Phaser.Game(1024, 768, Phaser.AUTO, 'phaser-example', null, false, true); - -game.state.add('Boot', BasicGame.Boot); -game.state.add('Preloader', BasicGame.Preloader); -game.state.add('MainMenu', BasicGame.MainMenu); - -game.state.start('Boot', true, false, 'hello', 'world'); diff --git a/examples/wip/tab swap.js b/examples/wip/tab swap.js deleted file mode 100644 index e9f7c33e3..000000000 --- a/examples/wip/tab swap.js +++ /dev/null @@ -1,97 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.audio('boden', ['assets/audio/bodenstaendig_2000_in_rock_4bit.mp3', 'assets/audio/bodenstaendig_2000_in_rock_4bit.ogg']); - -} - -var mummy; -var anim; -var music; -var s = []; - -function create() { - - game.stage.backgroundColor = 0x3d4d3d; - - music = game.add.audio('boden'); - music.play(); - - mummy = game.add.sprite(500, 300, 'mummy', 5); - mummy.scale.set(2); - - anim = mummy.animations.add('walk'); - - anim.play(10, true); - - game.onPause.add(paused, this); - game.onResume.add(resumed, this); - - var space = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); - space.onDown.add(muteToggle, this); - - s.push('starting: ' + game.stage._hiddenVar); - -} - -function muteToggle() { - - if (game.sound.mute) - { - game.sound.mute = false; - } - else - { - game.sound.mute = true; - } - -} - -function pauseToggle() { - - if (game.paused) - { - game.paused = false; - } - else - { - game.paused = true; - } - -} - -function paused() { - - s.push('paused now: ' + game.time.now); - // console.log('paused now:', game.time.now); - -} - -function resumed() { - - s.push('resumed now: ' + game.time.now); - s.push('pause duration: ' + game.time.pauseDuration); - // console.log('resumed now:', game.time.now); - // console.log('resumed duration:', game.time.pauseDuration); - -} - -function update() { - -} - -function render() { - - // game.debug.text(anim.frame + ' / 17', 32, 32); - - for (var i = 0; i < s.length; i++) - { - game.debug.text(s[i], 16, 160 + (16 * i)); - } - - game.debug.soundInfo(music, 20, 32); - -} \ No newline at end of file diff --git a/examples/wip/template.js b/examples/wip/template.js deleted file mode 100644 index 544dd8f3c..000000000 --- a/examples/wip/template.js +++ /dev/null @@ -1,22 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - -} - -var sprite; - -function create() { - -} - -function update() { - - -} - -function render() { - -} diff --git a/examples/wip/text tilesprite.js b/examples/wip/text tilesprite.js deleted file mode 100644 index ebe3bb899..000000000 --- a/examples/wip/text tilesprite.js +++ /dev/null @@ -1,60 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update }); -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('knightHawks', 'assets/fonts/KNIGHT3.png'); - game.load.script('filter', '../filters/Plasma.js'); - -} - -var font; -var i; -var background; -var filter; -var count = 0; - -function create() { - - game.world.setBounds(0, 0, 2000, 600); - - background = game.add.sprite(0, 0); - background.width = 800; - background.height = 600; - - filter = game.add.filter('Plasma', 800, 600); - - background.filters = [filter]; - - font = game.add.bitmapFont('knightHawks', 31, 25, Phaser.BitmapFont.TEXT_SET6, 10, 1, 1); - font.text = 'phaser '; - - // i = game.add.image(0, 0, font); - - sprite = game.add.tileSprite(0, 0, 800, 600, font); - -} - -function update() { - - count += 0.005 - - sprite.tileScale.x = 2 + Math.sin(count); - sprite.tileScale.y = 2 + Math.cos(count); - - sprite.tilePosition.x += 1; - sprite.tilePosition.y += 1; - - - // game.camera.view.x++; - - filter.update(); - - // Uncomment for coolness :) - // filter.blueShift -= 0.001; - - font.text = " phaser x: " + game.input.x + " y: " + game.input.y; - sprite.refreshTexture = true; - -} diff --git a/examples/wip/text tween.js b/examples/wip/text tween.js deleted file mode 100644 index e1d240a06..000000000 --- a/examples/wip/text tween.js +++ /dev/null @@ -1,46 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create }); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var text; -var b; -var grd; - -function create() { - - game.stage.setBackgroundColor(0x2d2d2d); - - text = game.add.text(game.world.centerX, game.world.centerY, "- phaser -\nwith a sprinkle of\npixi dust"); - text.anchor.set(0.5); - - text.font = 'Art of Fighting 2'; - // text.font = 'Arial Black'; - text.fontSize = 20; - text.fontWeight = 'bold'; - - // x0, y0 - x1, y1 - grd = text.context.createLinearGradient(0, 0, 0, text.canvas.height); - grd.addColorStop(0, '#8ED6FF'); - grd.addColorStop(1, '#004CB3'); - text.fill = grd; - - // text.fill = '#ff0044'; - // text.lineSpacing = 16; - text.align = 'center'; - text.stroke = '#000000'; - text.strokeThickness = 2; - - // text.setShadow(5, 5, 'rgba(0,0,0,0.5)', 5); - - // text.scale.set(4); - - // game.add.tween(text).to({fontSize: 60}, 1000, Phaser.Easing.Linear.None,true); - game.add.tween(text.scale).to({x: 6, y: 6}, 2000, Phaser.Easing.Linear.None,true); - -} - diff --git a/examples/wip/text.js b/examples/wip/text.js deleted file mode 100644 index 885d7bdf2..000000000 --- a/examples/wip/text.js +++ /dev/null @@ -1,83 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('pic', 'assets/pics/backscroll.png'); - -} - -var text; -var b; -var grd; - -function create() { - - game.stage.setBackgroundColor(0x2d2d2d); - - text = game.add.text(game.world.centerX, game.world.centerY, "- phaser -\nwith a sprinkle of\npixi dust"); - // text = game.add.text(game.world.centerX, game.world.centerY, "- phaser - with a sprinkle of pixi dust"); - - text.anchor.setTo(0.5); - - // text.font = 'Art of Fighting 2'; - text.font = 'Arial Black'; - text.fontSize = 60; - text.fontWeight = 'bold'; - - // x0, y0 - x1, y1 - grd = text.context.createLinearGradient(0, 0, 0, text.canvas.height); - grd.addColorStop(0, '#8ED6FF'); - grd.addColorStop(1, '#004CB3'); - text.fill = grd; - - // text.fill = '#ff0044'; - // text.lineSpacing = 16; - text.align = 'center'; - text.stroke = '#000000'; - text.strokeThickness = 2; - - text.setShadow(5, 5, 'rgba(0,0,0,0.5)', 5); - // text.wordWrap = true; - // text.wordWrapWidth = 50; - - // game.input.onDown.add(change, this); - - text.inputEnabled = true; - text.input.enableDrag(); - - text.events.onInputOver.add(over, this); - text.events.onInputOut.add(out, this); - -} - -function out() { - - text.fill = grd; - -} - -function over() { - - text.fill = '#ff00ff'; - -} - -function change() { - - // text.tint = Math.random() * 0xFFFFFF; - -} - -function update() { - // b = text.getBounds(); - - -} - -function render() { - - // game.debug.geom(b); - // game.debug.text(sprite.position.y, 32, 32); - -} diff --git a/examples/wip/tilemap blank.js b/examples/wip/tilemap blank.js deleted file mode 100644 index 2b2829d7f..000000000 --- a/examples/wip/tilemap blank.js +++ /dev/null @@ -1,117 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - -} - -var map; -var layer; - -var marker; -var currentTile = 0; -var cursors; - -function create() { - - game.stage.backgroundColor = '#787878'; - - // Creates a blank tilemap - map = game.add.tilemap(); - - // Creates a layer and sets-up the map dimensions. - // In this case the map is 30x30 tiles in size and the tiles are 32x32 pixels in size. - map.create('level1', 30, 30, 32, 32); - - // Add a Tileset image to the map - map.addTilesetImage('ground_1x1'); - - // Create a layer. This is where the map is rendered to. - layer = map.createLayer('level1'); - - // Resize the world - layer.resizeWorld(); - - // Create our tile selector at the top of the screen - createTileSelector(); - - game.input.setMoveCallback(updateMarker, this); - - console.log(map.tiles); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function pickTile(sprite, pointer) { - - currentTile = game.math.snapToFloor(pointer.x, 32) / 32; - - console.log(map.tiles[currentTile]); - -} - -function updateMarker() { - - marker.x = layer.getTileX(game.input.activePointer.worldX) * 32; - marker.y = layer.getTileY(game.input.activePointer.worldY) * 32; - - if (game.input.mousePointer.isDown) - { - map.putTile(currentTile, layer.getTileX(marker.x), layer.getTileY(marker.y)) - } - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - -} - -function render() { - -} - -function createTileSelector() { - - // Our tile selection window - var tileSelector = game.add.group(); - - var tileSelectorBackground = game.make.graphics(); - tileSelectorBackground.beginFill(0x000000, 0.5); - tileSelectorBackground.drawRect(0, 0, 800, 34); - tileSelectorBackground.endFill(); - - tileSelector.add(tileSelectorBackground); - - var tileStrip = tileSelector.create(1, 1, 'ground_1x1'); - tileStrip.inputEnabled = true; - tileStrip.events.onInputDown.add(pickTile, this); - - tileSelector.fixedToCamera = true; - - // Our painting marker - marker = game.add.graphics(); - marker.lineStyle(2, 0x000000, 1); - marker.drawRect(0, 0, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/tilemap csv.js b/examples/wip/tilemap csv.js deleted file mode 100644 index e3fd675b8..000000000 --- a/examples/wip/tilemap csv.js +++ /dev/null @@ -1,59 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/csv/catastrophi_level2.csv', null, Phaser.Tilemap.CSV); - game.load.image('tiles', 'assets/tilemaps/tiles/catastrophi_tiles_16.png'); - -} - -var map; -var layer; -var cursors; - -function create() { - - // Because we're loading CSV map data we have to specify the tile size here or we can't render it - map = game.add.tilemap('map', 16, 16); - - // Now add in the tileset - map.addTilesetImage('tiles'); - - // Create our layer - layer = map.createLayer(0); - - // Resize the world - layer.resizeWorld(); - - // Allow cursors to scroll around the map - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - -} - -function render() { - -} diff --git a/examples/wip/tilemap new 1.js b/examples/wip/tilemap new 1.js deleted file mode 100644 index be8de6ecb..000000000 --- a/examples/wip/tilemap new 1.js +++ /dev/null @@ -1,77 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - -} - -var map; -var layer; -var cursors; -var sprite; - -function create() { - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - map.setCollisionBetween(1, 12); - - // layer.debug = true; - - sprite = game.add.sprite(260, 70, 'phaser'); - - game.physics.enable(sprite); - - sprite.body.bounce.set(0.8); - sprite.body.tilePadding.set(32); - - game.camera.follow(sprite); - - game.physics.arcade.gravity.y = 200; - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - game.physics.arcade.collide(sprite, layer); - - // sprite.body.velocity.x = 0; - // sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - } - -} - -function render() { - - // game.debug.body(sprite); - -} diff --git a/examples/wip/tilemap put tile.js b/examples/wip/tilemap put tile.js deleted file mode 100644 index ed57813a4..000000000 --- a/examples/wip/tilemap put tile.js +++ /dev/null @@ -1,117 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - -} - -var map; -var layer; - -var marker; -var currentTile = 0; -var cursors; - -function create() { - - game.stage.backgroundColor = '#787878'; - - // Creates a blank tilemap - map = game.add.tilemap(); - - // Creates a layer and sets-up the map dimensions. - // In this case the map is 30x30 tiles in size and the tiles are 32x32 pixels in size. - map.create('level1', 30, 30, 32, 32); - - // Add a Tileset image to the map - map.addTilesetImage('ground_1x1'); - - // Create a layer. This is where the map is rendered to. - layer = map.createLayer('level1'); - - // Resize the world - layer.resizeWorld(); - - map.setCollisionBetween(0, 12); - - layer.debug = true; - - // Create our tile selector at the top of the screen - createTileSelector(); - - game.input.setMoveCallback(updateMarker, this); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function pickTile(sprite, pointer) { - - currentTile = game.math.snapToFloor(pointer.x, 32) / 32; - -} - -function updateMarker() { - - marker.x = layer.getTileX(game.input.activePointer.worldX) * 32; - marker.y = layer.getTileY(game.input.activePointer.worldY) * 32; - - if (game.input.mousePointer.isDown) - { - map.putTile(currentTile, layer.getTileX(marker.x), layer.getTileY(marker.y)) - } - -} - -function update() { - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - -} - -function render() { - -} - -function createTileSelector() { - - // Our tile selection window - var tileSelector = game.add.group(); - - var tileSelectorBackground = game.make.graphics(); - tileSelectorBackground.beginFill(0x000000, 0.5); - tileSelectorBackground.drawRect(0, 0, 800, 34); - tileSelectorBackground.endFill(); - - tileSelector.add(tileSelectorBackground); - - var tileStrip = tileSelector.create(1, 1, 'ground_1x1'); - tileStrip.inputEnabled = true; - tileStrip.events.onInputDown.add(pickTile, this); - - tileSelector.fixedToCamera = true; - - // Our painting marker - marker = game.add.graphics(); - marker.lineStyle(2, 0x000000, 1); - marker.drawRect(0, 0, 32, 32); - -} \ No newline at end of file diff --git a/examples/wip/tilemap raycast.js b/examples/wip/tilemap raycast.js deleted file mode 100644 index c074a92cb..000000000 --- a/examples/wip/tilemap raycast.js +++ /dev/null @@ -1,127 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('phaser', 'assets/sprites/phaser-dude.png'); - -} - -var map; -var layer; -var cursors; -var sprite; -var line; -var tileHits = []; -var plotting = false; - -function create() { - - line = new Phaser.Line(); - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - - layer = map.createLayer('Tile Layer 1'); - - layer.resizeWorld(); - - map.setCollisionBetween(1, 12); - - layer.debug = true; - - sprite = game.add.sprite(260, 70, 'phaser'); - - game.physics.enable(sprite); - - game.camera.follow(sprite); - - cursors = game.input.keyboard.createCursorKeys(); - - var help = game.add.text(10, 10, 'Arrows to move, click and drag to cast a ray', { font: '16px Arial', fill: '#ffffff' }); - help.fixedToCamera = true; - - game.input.onDown.add(startLine, this); - game.input.onUp.add(raycast, this); - -} - -function startLine(pointer) { - - if (tileHits.length > 0) - { - for (var i = 0; i < tileHits.length; i++) - { - tileHits[i].debug = false; - } - - layer.dirty = true; - } - - line.start.set(pointer.worldX, pointer.worldY); - - plotting = true; - -} - -function raycast(pointer) { - - line.end.set(pointer.worldX, pointer.worldY); - - tileHits = layer.getRayCastTiles(line, 4, false, false); - - if (tileHits.length > 0) - { - // Just so we can visually see the tiles - for (var i = 0; i < tileHits.length; i++) - { - tileHits[i].debug = true; - } - - layer.dirty = true; - } - - plotting = false; - -} - -function update() { - - if (plotting) - { - line.end.set(game.input.activePointer.worldX, game.input.activePointer.worldY); - } - - game.physics.arcade.collide(sprite, layer); - - sprite.body.velocity.x = 0; - sprite.body.velocity.y = 0; - - if (cursors.up.isDown) - { - sprite.body.velocity.y = -200; - } - else if (cursors.down.isDown) - { - sprite.body.velocity.y = 200; - } - - if (cursors.left.isDown) - { - sprite.body.velocity.x = -200; - } - else if (cursors.right.isDown) - { - sprite.body.velocity.x = 200; - } - -} - -function render() { - - game.debug.geom(line); - -} diff --git a/examples/wip/tilemap1.js b/examples/wip/tilemap1.js deleted file mode 100644 index a297a1be8..000000000 --- a/examples/wip/tilemap1.js +++ /dev/null @@ -1,165 +0,0 @@ - -// var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('walls_1x2', 'assets/tilemaps/tiles/walls_1x2.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - game.load.image('player', 'assets/sprites/phaser-dude.png'); - game.load.image('box', 'assets/sprites/ufo.png'); - game.load.image('ship', 'assets/sprites/thrust_ship2.png'); - -} - -var ship; -var map; -var tileset; -var layer; -var p; -var b; -var cursors; -var box2; -var dump; - -function create() { - - game.physics.startSystem(Phaser.Physics.P2JS); - - game.stage.backgroundColor = '#787878'; - - map = game.add.tilemap('map'); - - map.addTilesetImage('ground_1x1'); - map.addTilesetImage('walls_1x2'); - map.addTilesetImage('tiles2'); - - layer = map.createLayer('Tile Layer 1'); - - // layer.resizeWorld(); - - map.setCollisionBetween(1, 12); - - // layer.debug = true; - - dump = map.generateCollisionData(layer); - - // dump = map.createCollisionObjects('collision'); - - // console.log(dump); - // console.log(dump[7]); - - - // ship = game.add.sprite(200, 200, 'ship'); - // ship.physicsEnabled = true; - - - - // p = game.add.sprite(32, 32, 'player'); - - // b = game.add.sprite(300, 300, 'player'); - // b.physicsEnabled = true; - // b.body.static = true; - // b.body.mass = 1; - // b.body.data.motionState = 2; - - // b.body.kinematic = true; - // b.body.clearShapes(); - // b.body.addLine(64, 0, 0, 0); - // b.body.fixedRotation = true; - // b.body.static = true; - - // var data = [[0,0] , [0, -32] , [32, -64] , [64, -64] , [64,-96], [128,-96], [160,-128], [192,-128], [192,-96], [160,-64], [96,-64], [96,-32], [32,-32], [32,0], [0,0]]; - // b = game.physics.createBody(192, 352, 0, true, { removeCollinearPoints: true }, data); - // b = game.physics.createBody(32, 32, 0, true, { removeCollinearPoints: true }, data); - // b = game.physics.createBody(256, 480, 0, true, { removeCollinearPoints: true }, data); - - // console.log('DATA'); - // console.log(data); - - // var re = b.body.addPolygon({removeCollinearPoints:true}, data); - // var re = b.body.addPolygon({removeCollinearPoints:true}, data); - - // console.log(data.length); - // console.log(re); - // console.log(output); - // console.log(b.body.data.shapes[0].vertices); - - box2 = game.add.sprite(200, 200, 'box'); - game.physics.p2.enable(box2); - box2.body.fixedRotation = true; - - game.camera.follow(box2); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - box2.body.setZeroVelocity(); - - if (cursors.left.isDown) - { - box2.body.moveLeft(200); - } - else if (cursors.right.isDown) - { - box2.body.moveRight(200); - } - - if (cursors.up.isDown) - { - box2.body.moveUp(200); - } - else if (cursors.down.isDown) - { - box2.body.moveDown(200); - } - -/* if (cursors.left.isDown) - { - ship.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - ship.body.rotateRight(100); - } - else - { - ship.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - ship.body.thrust(400); - } -*/ - - -} - -function render() { - - // game.debug.cameraInfo(game.camera, 420, 320); - - // game.debug.text(box2.body.velocity.x, 32, 32); - // game.debug.text(box2.body.velocity.y, 32, 64); - - // game.debug.text(b.body.velocity.x, 32, 32); - // game.debug.text(b.body.velocity.y, 32, 64); - - // for (var i = 0, len = dump.length; i < len; i++) - // { - // game.debug.physicsBody(dump[i]); - // } - - // game.debug.physicsBody(dump[0]); - // game.debug.physicsBody(b); - - // game.debug.physicsBody(ship.body); - - -} diff --git a/examples/wip/tilemap2.js b/examples/wip/tilemap2.js deleted file mode 100644 index 91a62fbd5..000000000 --- a/examples/wip/tilemap2.js +++ /dev/null @@ -1,86 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/collision_test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('ground_1x1', 'assets/tilemaps/tiles/ground_1x1.png'); - game.load.image('tiles2', 'assets/tilemaps/tiles/tiles2.png'); - game.load.image('ufo', 'assets/sprites/ufo.png'); - game.load.image('ship', 'assets/sprites/thrust_ship2.png'); - -} - -var ship; -var map; -var layer; -var cursors; -var dump; - -function create() { - - game.stage.backgroundColor = '#2d2d2d'; - - // map = game.add.tilemap('map'); - - // map.addTilesetImage('ground_1x1'); - // map.addTilesetImage('tiles2'); - - // map.setCollisionBetween(1, 12); - - // layer = map.createLayer('Tile Layer 1'); - - // layer.resizeWorld(); - - // dump = map.generateCollisionData(layer); - - ship = game.add.sprite(200, 200, 'ship'); - ship.physicsEnabled = true; - // We do this because our ship is shaped like a triangle, not a square :) - ship.body.addPolygon({}, 29, 23 , 0, 23 , 14, 1); - // ship.body.setCircle(32); - // ship.body.setCircle(32, 20, 20); - - game.camera.follow(ship); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - ship.body.rotateLeft(100); - } - else if (cursors.right.isDown) - { - ship.body.rotateRight(100); - } - else - { - ship.body.setZeroRotation(); - } - - if (cursors.up.isDown) - { - ship.body.thrust(400); - } - else if (cursors.down.isDown) - { - ship.body.reverse(400); - } - -} - -function render() { - - // for (var i = 0, len = dump.length; i < len; i++) - // { - // game.debug.physicsBody(dump[i]); - // } - - game.debug.physicsBody(ship.body); - -} diff --git a/examples/wip/tilemap3.js b/examples/wip/tilemap3.js deleted file mode 100644 index eb3e62e2f..000000000 --- a/examples/wip/tilemap3.js +++ /dev/null @@ -1,41 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); -// var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.tilemap('map', 'assets/tilemaps/maps/test.json', null, Phaser.Tilemap.TILED_JSON); - game.load.image('tileset', 'assets/tilemaps/tiles/test.png'); - -} - -var map; -var layer; - -function create() { - - game.stage.backgroundColor = '#787878'; - - map = game.add.tilemap('map'); - - map.addTilesetImage('tileset'); - - layer = map.createLayer('calque1'); - - console.log(layer); - - // layer.resizeWorld(); - - // map.setCollisionBetween(1, 12); - - // layer.debug = true; - - // dump = map.generateCollisionData(layer); - -} - -function update() { -} - -function render() { -} diff --git a/examples/wip/tilesprite fixed to cam.js b/examples/wip/tilesprite fixed to cam.js deleted file mode 100644 index df157af6f..000000000 --- a/examples/wip/tilesprite fixed to cam.js +++ /dev/null @@ -1,60 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('starfield', 'assets/misc/starfield.jpg'); - -} - -var sprite; -var cursors; -var mushroom; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.image(0, 0, 'backdrop'); - - sprite = game.add.tileSprite(100, 100, 200, 200, 'starfield'); - sprite.autoScroll(0, 100); - sprite.fixedToCamera = true; - console.log(sprite.parent); - - mushroom = game.add.sprite(400, 400, 'mushroom'); - - game.camera.follow(mushroom); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.left.isDown) - { - mushroom.x -= 8; - } - else if (cursors.right.isDown) - { - mushroom.x += 8; - } - - if (cursors.up.isDown) - { - mushroom.y -= 8; - } - else if (cursors.down.isDown) - { - mushroom.y += 8; - } - -} - -function render() { - - // game.debug.text(sprite.frame, 32, 32); - -} diff --git a/examples/wip/tilesprite input.js b/examples/wip/tilesprite input.js deleted file mode 100644 index 648b40a1d..000000000 --- a/examples/wip/tilesprite input.js +++ /dev/null @@ -1,67 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.image('backdrop', 'assets/pics/remember-me.jpg'); - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('starfield', 'assets/misc/starfield.jpg'); - -} - -var sprite; -var cursors; -var mushroom; - -function create() { - - game.world.setBounds(0, 0, 1920, 1200); - game.add.image(0, 0, 'backdrop'); - - sprite = game.add.tileSprite(100, 100, 200, 200, 'starfield'); - sprite.inputEnabled = true; - sprite.events.onInputDown.add(scroll, this); - sprite.input.enableDrag(); - - mushroom = game.add.sprite(400, 400, 'mushroom'); - mushroom.inputEnabled = true; - mushroom.input.enableDrag(); - - game.camera.follow(mushroom); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function scroll() -{ - sprite.autoScroll(0, 100); -} - -function update() { - - if (cursors.left.isDown) - { - mushroom.x -= 8; - } - else if (cursors.right.isDown) - { - mushroom.x += 8; - } - - if (cursors.up.isDown) - { - mushroom.y -= 8; - } - else if (cursors.down.isDown) - { - mushroom.y += 8; - } - -} - -function render() { - - // game.debug.text(sprite.frame, 32, 32); - -} diff --git a/examples/wip/tilesprite.js b/examples/wip/tilesprite.js deleted file mode 100644 index c5d147c6f..000000000 --- a/examples/wip/tilesprite.js +++ /dev/null @@ -1,64 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -var tilesprite; -var cursors; - -function preload() { - - game.load.image('starfield', 'assets/misc/starfield.jpg'); - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - game.load.atlas('seacreatures', 'assets/sprites/seacreatures_json.png', 'assets/sprites/seacreatures_json.json'); - -} - -var sprite; - -function create() { - - // sprite = game.add.tileSprite(0, 0, 800, 600, 'starfield'); - - // sprite = game.add.tileSprite(100, 100, 400, 300, 'starfield'); - - sprite = game.add.tileSprite(100, 100, 400, 300, 'mummy'); - sprite.pivot.setTo(200, 200); - - sprite.animations.add('walk'); - - sprite.animations.play('walk', 20, true); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - sprite.rotation += 0.01; - - if (cursors.left.isDown) - { - sprite.tilePosition.x += 8; - sprite.x -= 4; - } - else if (cursors.right.isDown) - { - sprite.tilePosition.x -= 8; - sprite.x += 4; - } - - if (cursors.up.isDown) - { - sprite.tilePosition.y += 8; - } - else if (cursors.down.isDown) - { - sprite.tilePosition.y -= 8; - } - -} - -function render() { - - game.debug.text(sprite.frame, 32, 32); - -} diff --git a/examples/wip/timer1.js b/examples/wip/timer1.js deleted file mode 100644 index 794d0e8ec..000000000 --- a/examples/wip/timer1.js +++ /dev/null @@ -1,29 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create }); - -var last; -var i = 0; - -function create() { - - //Maybe you have to set it even lower for your machine. - //It's related to the time Phaser needs to boot up. - //The tick stops being negative and behaves nearly normal for me at around 550 - 600ms - - delay = 250; - foreverTimer = game.time.events.repeat(delay, 10, handleEvent, this); - - last = Date.now(); - - console.log('create started', last); - -} - -function handleEvent() { - - console.log('>> Tick', i, 'ms diff:', Date.now() - last); - - last = Date.now(); - - i++; - -} \ No newline at end of file diff --git a/examples/wip/timer2.js b/examples/wip/timer2.js deleted file mode 100644 index 8ee7b71c8..000000000 --- a/examples/wip/timer2.js +++ /dev/null @@ -1,42 +0,0 @@ -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { create: create}); -var counter = 0 -var explicitlyPaused = false - -function create() { - game.stage.backgroundColor = '#6688ee'; - timer = game.time.create(false); - timer.repeat(Phaser.Timer.SECOND, 10, step, this); - - game.onPause.add(handleGamePaused) - game.onResume.add(handleGameResumed) - - //prevent init tick error - setTimeout(function(){ - timer.start() - }, 250) - -} -function handleGamePaused(){ - console.log('game paused') -} -function handleGameResumed(){ - console.log('game resumed') -} - -function step(){ - counter++ - console.log('timer step', counter) - - if(counter == 3){ - pauseTimer() - } - if(counter > 3){ - console.log('this should never happen! Paused since step #3') - } -} -function pauseTimer(){ - if(explicitlyPaused) return - console.log('pause timer triggered') - explicitlyPaused = true - timer.pause() -} \ No newline at end of file diff --git a/examples/wip/tween generate 2.js b/examples/wip/tween generate 2.js deleted file mode 100644 index 8d5c010c2..000000000 --- a/examples/wip/tween generate 2.js +++ /dev/null @@ -1,88 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('wasp', 'assets/sprites/wasp.png'); - game.load.image('sky', 'assets/skies/cavern1.png'); - -} - -var bugs; -var index = 0; -var data; -var pos = []; - -function create() { - - game.add.image(0, 0, 'sky'); - - // image = game.add.image(0, 0, 'wasp'); - - // We don't want it to actually run, so we use game.make.tween instead of game.add.tween - - var tweenData = { x: 0, y: 0 }; - - // Here we'll tween the values held in the tweenData object to x: 500, y: 300 - tween = game.make.tween(tweenData).to( { x: 100, y: 400 }, 2000, Phaser.Easing.Sinusoidal.InOut); - - // Set the tween to yoyo so it loops smoothly - tween.yoyo(true); - - // We have 3 interpolation methods available: linearInterpolation (the default), bezierInterpolation and catmullRomInterpolation. - - // tween.interpolation(game.math.bezierInterpolation); - tween.interpolation(game.math.catmullRomInterpolation); - - // Generates the tween data at a rate of 60 frames per second. - // This is useful if you've got a lot of objects all using the same tween, just at different coordinates. - // It saves having to calculate the same tween across the properties of all objects involved in the motion. - // Instead you can pre-calculate it in advance and trade that in for a bit of memory to store it in an array. - data = tween.generateData(60); - - // Now create some sprites to shown the tween data in action - bugs = game.add.group(); - - pos.push(new Phaser.Point(32, 0)); - pos.push(new Phaser.Point(300, 100)); - pos.push(new Phaser.Point(600, 70)); - - bugs.create(pos[0].x, pos[0].y, 'wasp'); - bugs.create(pos[1].x, pos[1].y, 'wasp'); - bugs.create(pos[2].x, pos[2].y, 'wasp'); - -} - -function update() { - - // A simple data playback. - - // Each element of the array contains an object that includes whatever properties were tweened - // In this case the x and y properties - - // Because the tween data is pre-generated we can apply it however we want: - // Directly, by adding to the coordinates - bugs.getAt(0).x = pos[0].x + data[index].x; - bugs.getAt(0).y = pos[0].y + data[index].y; - - // Half one of the values - bugs.getAt(1).x = pos[1].x + (data[index].x / 2); - bugs.getAt(1).y = pos[1].y + data[index].y; - - // Inverse one of the values - bugs.getAt(2).x = pos[2].x - data[index].x; - bugs.getAt(2).y = pos[2].y + data[index].y; - - // You can do all kinds of effects by modifying the tween data, - // without having loads of active tweens running. - - // This just advances the tween data index - // It's crude and doesn't take target device speed into account at all, but works as an example - index++; - - if (index === data.length) - { - index = 0; - } - -} diff --git a/examples/wip/tween generate.js b/examples/wip/tween generate.js deleted file mode 100644 index 432a66b67..000000000 --- a/examples/wip/tween generate.js +++ /dev/null @@ -1,77 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update }); - -function preload() { - - game.load.image('wasp', 'assets/sprites/wasp.png'); - game.load.image('sky', 'assets/skies/sky5.png'); - -} - -var bugs; -var index = 0; -var data; - -function create() { - - game.add.image(0, 0, 'sky'); - - // image = game.add.image(0, 0, 'wasp'); - - // We don't want it to actually run, so we use game.make.tween instead of game.add.tween - - var tweenData = { x: 0, y: 0 }; - - // Here we'll tween the values held in the tweenData object to x: 500, y: 300 - tween = game.make.tween(tweenData).to( { x: 100, y: 500 }, 2000, Phaser.Easing.Sinusoidal.InOut); - - // Set the tween to yoyo so it loops smoothly - tween.yoyo(true); - - // We have 3 interpolation methods available: linearInterpolation (the default), bezierInterpolation and catmullRomInterpolation. - - // tween.interpolation(game.math.bezierInterpolation); - tween.interpolation(game.math.catmullRomInterpolation); - - // Generates the tween data at a rate of 60 frames per second. - // This is useful if you've got a lot of objects all using the same tween, just at different coordinates. - // It saves having to calculate the same tween across the properties of all objects involved in the motion. - // Instead you can pre-calculate it in advance and trade that in for a bit of memory to store it in an array. - data = tween.generateData(60); - - // Now create some sprites to shown the tween data in action - bugs = game.add.group(); - - bugs.create(100, 0, 'wasp'); - bugs.create(300, 100, 'wasp'); - bugs.create(600, 30, 'wasp'); - -} - -function update() { - - // A simple data playback. - - // Each element of the array contains an object that includes whatever properties were tweened - // In this case the x and y properties - - bugs.getAt(0).x = data[index].x; - bugs.getAt(0).y += data[index].y; - - bugs.getAt(1).x += data[index].x; - bugs.getAt(1).y += data[index].y; - - bugs.getAt(2).x += data[index].x; - bugs.getAt(2).y += data[index].y; - - - // image.x = data[index].x; - // image.y = data[index].y; - index++; - - if (index === data.length) - { - index = 0; - } - -} diff --git a/examples/wip/tween swap.js b/examples/wip/tween swap.js deleted file mode 100644 index 2490036c8..000000000 --- a/examples/wip/tween swap.js +++ /dev/null @@ -1,95 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; -var anim; -var s = []; -var t; - -function create() { - - game.stage.backgroundColor = 0x3d4d3d; - - mummy = game.add.sprite(0, 300, 'mummy', 5); - // mummy.scale.set(2); - - anim = mummy.animations.add('walk'); - - anim.play(10, true); - - // game.onPause.add(paused, this); - // game.onResume.add(resumed, this); - - game.add.tween(mummy.scale).to({x:4,y:4}, 1000, Phaser.Easing.Linear.None, true); - t = game.add.tween(mummy).to({x:700}, 15000, Phaser.Easing.Linear.None, true); - t.onComplete.add(tweenOver, this); - - s.push('starting: ' + game.stage._hiddenVar); - - game.input.onDown.add(pauseTween, this); - -} - -function pauseTween(pointer) { - - if (pointer.x < 400) - { - t.pause(); - } - else - { - t.resume(); - } - -} - -function tweenOver() { - console.log('yay all over after 15 seconds anyway'); -} - -/*function pauseToggle() { - - if (game.paused) - { - game.paused = false; - } - else - { - game.paused = true; - } - -} -function paused() { - - s.push('paused now: ' + game.time.now); - console.log('paused now: ' + game.time.now); - -} - -function resumed() { - - s.push('resumed now: ' + game.time.now); - console.log('resumed now: ' + game.time.now); - s.push('pause duration: ' + game.time.pauseDuration); - -} -*/ - -function update() { - -} - -function render() { - - for (var i = 0; i < s.length; i++) - { - game.debug.text(s[i], 16, 160 + (16 * i)); - } - -} \ No newline at end of file diff --git a/examples/wip/tween var.js b/examples/wip/tween var.js deleted file mode 100644 index 2287ac3b4..000000000 --- a/examples/wip/tween var.js +++ /dev/null @@ -1,39 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.load.spritesheet('mummy', 'assets/sprites/metalslug_mummy37x45.png', 37, 45, 18); - -} - -var mummy; - -function create() { - - game.stage.backgroundColor = 0x3d4d3d; - - mummy = game.add.sprite(300, 300, 'mummy', 5); - - var t = game.add.tween(mummy).to( { "x": 400, "y": 400 }, 5000, Phaser.Easing.Linear.None, true); - - // var t = game.add.tween(mummy).to( { "scale.x": 4, "scale.y": 4 }, 5000, Phaser.Easing.Linear.None, true); - - t.onComplete.add(tweenOver, this); - -} - -function tweenOver(a) { - - console.log('over'); - console.log(a); - -} - -function update() { - -} - -function render() { - -} \ No newline at end of file diff --git a/examples/wip/twokeys.js b/examples/wip/twokeys.js deleted file mode 100644 index 2ef903f2a..000000000 --- a/examples/wip/twokeys.js +++ /dev/null @@ -1,33 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - -} - -var text; -var key1; -var key2; - -function create() { - - game.stage.setBackgroundColor(0x0b7276); - - game.add.text(32, 16, "SPACE"); - game.add.text(32, 170, "A"); - - key1 = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR); - key2 = game.input.keyboard.addKey(Phaser.Keyboard.A); - -} - -function update() { - -} - -function render() { - - game.debug.key(key1, 32, 64); - game.debug.key(key2, 32, 220); - -} diff --git a/examples/world/fixed to camera.js b/examples/world/fixed to camera.js deleted file mode 100644 index 6585afc08..000000000 --- a/examples/world/fixed to camera.js +++ /dev/null @@ -1,75 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render : render }); - -function preload() { - - game.stage.backgroundColor = '#007236'; - - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('sonic', 'assets/sprites/sonic_havok_sanity.png'); - game.load.image('phaser', 'assets/sprites/phaser1.png'); - -} - -var cursors; -var logo1; -var logo2; - -function create() { - - // Modify the world and camera bounds - game.world.setBounds(-1000, -1000, 2000, 2000); - - for (var i = 0; i < 200; i++) - { - game.add.sprite(game.world.randomX, game.world.randomY, 'mushroom'); - } - - game.add.text(0, 0, "this text scrolls\nwith the background", { font: "32px Arial", fill: "#f26c4f", align: "center" }); - - logo1 = game.add.sprite(0, 0, 'phaser'); - logo1.fixedToCamera = true; - logo1.cameraOffset.setTo(100, 100); - - logo2 = game.add.sprite(0, 0, 'phaser'); - logo2.fixedToCamera = true; - logo2.cameraOffset.setTo(500, 100); - - - var t = game.add.text(0, 0, "this text is fixed to the camera", { font: "32px Arial", fill: "#ffffff", align: "center" }); - t.fixedToCamera = true; - t.cameraOffset.setTo(200, 500); - - game.add.tween(logo2.cameraOffset).to( { y: 400 }, 2000, Phaser.Easing.Back.InOut, true, 0, 2000, true); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - if (cursors.up.isDown) - { - game.camera.y -= 4; - } - else if (cursors.down.isDown) - { - game.camera.y += 4; - } - - if (cursors.left.isDown) - { - game.camera.x -= 4; - } - else if (cursors.right.isDown) - { - game.camera.x += 4; - } - -} - -function render() { - - game.debug.cameraInfo(game.camera, 32, 32); - -} diff --git a/examples/world/move around world.js b/examples/world/move around world.js deleted file mode 100644 index cb1440b18..000000000 --- a/examples/world/move around world.js +++ /dev/null @@ -1,93 +0,0 @@ - -var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update, render: render }); - -function preload() { - - game.stage.backgroundColor = '#007236'; - - game.load.image('mushroom', 'assets/sprites/mushroom2.png'); - game.load.image('phaser', 'assets/sprites/sonic_havok_sanity.png'); - -} - -var cursors; -var d; - -function create() { - - // Modify the world and camera bounds - game.world.setBounds(-2000, -2000, 4000, 4000); - - for (var i = 0; i < 100; i++) - { - game.add.sprite(game.world.randomX, game.world.randomY, 'mushroom'); - } - - game.add.text(600, 800, "- phaser -", { font: "32px Arial", fill: "#330088", align: "center" }); - - d = game.add.sprite(0, 0, 'phaser'); - d.anchor.setTo(0.5, 0.5); - - cursors = game.input.keyboard.createCursorKeys(); - -} - -function update() { - - d.angle += 1; - - if (cursors.up.isDown) - { - if (cursors.up.shiftKey) - { - d.angle++; - } - else - { - game.camera.y -= 4; - } - } - else if (cursors.down.isDown) - { - if (cursors.down.shiftKey) - { - d.angle--; - } - else - { - game.camera.y += 4; - } - } - - if (cursors.left.isDown) - { - if (cursors.left.shiftKey) - { - game.world.rotation -= 0.05; - } - else - { - game.camera.x -= 4; - } - } - else if (cursors.right.isDown) - { - if (cursors.right.shiftKey) - { - game.world.rotation += 0.05; - } - else - { - game.camera.x += 4; - } - } - -} - -function render() { - - game.debug.cameraInfo(game.camera, 32, 32); - game.debug.spriteInfo(d, 32, 200); - game.debug.spriteCorners(d, false, true); - -} diff --git a/resources/Migration Guide.md b/resources/Migration Guide.md new file mode 100644 index 000000000..694533e80 --- /dev/null +++ b/resources/Migration Guide.md @@ -0,0 +1,157 @@ +Phaser 1.x to 2.0.0 Migration Guide +=================================== + +There are a number of significant API changes in Phaser 2.0. + +The following is a list of the most important, along with a small guide on updating your games to work. + +Please also see the Examples as we've updated every single one of them to work with 2.0. + +Updated to Pixi.js 1.5 +---------------------- + +This was a big change. Not only did we totally re-vamp the internals of Phaser as a result, we also now intelligently extend Pixi objects. + +* Group now extends PIXI.DisplayObjectContainer, rather than owning a _container property, which makes life a whole lot easier re: nesting and child iteration. +* Removed Sprite.group property. You can use Sprite.parent for all similar needs now. +* PIXI.Point is now aliased to Phaser.Point - saves on code duplication and works exactly the same. +* PIXI.Rectangle is now aliased to Phaser.Rectangle - saves on code duplication and works exactly the same. +* PIXI.Circle is now aliased to Phaser.Circle - saves on code duplication and works exactly the same. +* PixiPatch no longer needed, all features that it patched are now native in Pixi :) +* Phaser.Stage now extends PIXI.Stage, rather than containing a _stage object. + +Added Phaser.Image +------------------ + +A Phaser Image is like a Sprite, but it doesn't have any animation or physics capabilities. Use it for logos, backgrounds, etc. + +* Button now extends Phaser.Image not Phaser.Sprite, all the same functionality as before remains, just no animations or physics body. + +Stage updates +------------- + +Stage has been updated a lot and the Scale Manager has moved as well. + +* Stage.scale has been moved to Game.scale. The same game scaling properties exist as before, but now accessed via Game.scale instead. +* Stage.aspectRatio has been moved to StageScaleMode.sourceAspectRatio (so now game.scale.sourceAspectRatio) +* Stage.scaleMode has been moved to StageScaleMode.scaleMode (so now game.scale.scaleMode) +* Stage.fullScreenScaleMode has been moved to StageScaleMode.fullScreenScaleMode (so now game.scale.fullScreenScaleMode) +* Stage.canvas has been moved to Game.canvas (which used to be a reference to Stage.canvas, but is now the actual object). +* World preUpdate, update and postUpdate have all been moved to Stage. So all children are updated regardless where on the display list they live. +* Phaser.StageScaleMode has been renamed to ScaleManager and moved from the system folder to the core folder. It's still available under game.scale. +* If your game references the old Phaser.StageScaleMode consts like SHOW_ALL you need to update them to Phaser.ScaleManager, i.e. Phaser.ScaleManager.SHOW_ALL. + +Changes to Phaser.Sprite +------------------------ + +* Sprite.crop() now takes a Phaser.Rectangle instead of explicit parameters. +* By default Sprites no longer check if they are within the world bounds. It's quite an expensive process (calling getBounds every frame), so you have to enable directly. +* Sprite.deltaX and deltaY swapped to functions: Sprite.deltaX() and Sprite.deltaY() +* Removed: Sprite.offset, center, topLeft, topRight, bottomRight, bottomLeft and bounds, as no longer needed internally. Use Sprite.getBounds() to derive them. +* Sprite.input.pixelPerfect has been split into two: Sprite.input.pixelPerfectClick and Sprite.input.pixelPerfectOver (see new features) +* If you set Sprite.exists to false it will also set Sprite.visible to false and remove its body from the physics world (if it has one). +* If you set Sprite.exists to true it will also set Sprite.visible to true and add its body back into the physics world (if it has one). +* Phaser.Animation.frame now returns the frame of the current animation, rather than the global frame from the sprite sheet / atlas. +* Sprite.damage will now kill the Sprite if health is less than or equal to 0 (before it would only kill if less than zero) + +Better Text Handling +-------------------- + +* Text.content has been replaced with Text.text. The Text class has a lot of new methods, check the docs! +* BitmapText has had a bit of an overhaul - the signature for adding a BitmapText has changed to: x, y, font, text, size. See the docs and examples for details. + +Input Changes +------------- + +* The Keyboard class has had a complete overhaul. Phaser.Key objects are created automatically, there are fixes against duration and keys reset properly on visibility loss. +* Keyboard.removeKey has been removed. The way the new keyboard manager works means it's no longer required. +* When a game un-pauses (from a visibility loss) it resets all Input components. + +Game and Group Updates +---------------------- + +* Game no longer pauses if you've forced orientation and change it, also doesn't resize a NO_SCALE game. +* When adding a Group if the parent value is `null` the Group won't be added to the World, so you can add it when ready. If parent is `undefined` it's added by default. +* In Group.destroy the default for 'destroyChildren' was false. It's now `true` as this is a far more likely requirement when destroying a Group. +* RandomDataGenerator is now started on Game creation instead of boot. You can pass a seed array in the game config object (feature request #547) + +Tilemap Changes +--------------- + +* If using P2, after defining tiles that collide on a Tilemap, you need to call Tilemap.generateCollisionData(layer) to populate the physics world with the data required. + +Time Changes +------------ + +* Time.advancedTiming is a new boolean property. If true Time.fps, fpsMin, fpsMax, frames, msMin and msMax will be calculated, otherwise they remain at their defaults. +* Time.physicsElapsed is no longer bound or clamped, be wary of this if you use the value anywhere in your code. + +Misc Changes +------------ + +* All the Debug methods have had the word 'render' removed from the start. So where you did `debug.renderSpriteInfo` before, it's now just `debug.spriteInfo`. +* Debug methods that rendered geometry (Rectangle, Circle, Line, Point) have been merged into the single method: `Debug.geom`. +* Loader won't set crossOrigin on Images unless it's set to something. The default is false, it used to be '' and can be any valid string. +* BitmapData.addTo removed and enhanced BitmapData.add so it can accept either a single Sprite/Image or an Array of them. +* BitmapData has had all of the EaselJS functions removed. It was just taking up space and you can do it all via BitmapData.context directly. +* Cache.getImageKeys and similar has been removed, please use Cache.getKeys(Phaser.Cache.IMAGE) instead, this now supports all 10 Cache data types. +* Phaser.QuadTree has been made more generic and works with any rectangle, not just physics bodies. +* Animation.looped has been renamed to Animation.loop. It's a boolean you can toggle at run-time to turn on/off animation looping. + +Multiple Physics Systems +------------------------ + +In Phaser 1.x all you had was the Arcade Physics system. Under 2.x you can now have any physics system you like, and we include the awesome full-body P2.JS, Arcade Physics and Ninja Physics as standard, with Box2D and Chipmunk on the way. + +p2.js is excellent, offering lots of powerful features. However on mobile it doesn't take long before the frame rate starts to dive. This is no fault of p2, it's having to do a lot of heavy lifting math and mobiles just struggle. Even with just 50 bodies in the scene you can see it start to suffer. So I wanted to offer an option to devs. + +In Phaser 2 no Sprites have physics bodies as standard, they all need to be physics enabled (much in the same way you enable them for input). This helps keep things fast. Where-as in 1.x Phaser was spending a lot of time processing a physics Body it may never even use. + +Arcade Physics, back from the dead +---------------------------------- + +So we decided to go back and resurrect Arcade Physics. Not the broken SAT one in 1.1.4, but the one previous to that. We merged lots of the fixes made in 1.1.4 (things like process callbacks actually working properly) with the previously working separation code from 1.1.3. This means that existing 'old' games won't have to be ported over to p2 to run, they can just use Arcade Physics like before - the only difference being they'll need to enable the Sprite bodies. All those annoying/broken things about 1.1.4, like the way gravity and velocity are messed-up, are all fixed. + +Because physics is 'off' by default we created a Physics Manager via which you do things like 'enable p2' or 'add a physics body to this sprite'. You can actually have p2 and Arcade physics running together in the same game. p2 could be controlling whatever bodies you give it, and arcade the same. + +Here is how you activate the physics systems: + +`game.physics.startSystem(Phaser.Physics.ARCADE);` +`game.physics.startSystem(Phaser.Physics.P2JS);` +`game.physics.startSystem(Phaser.Physics.NINJA);` + +The important thing to remember is that a single Sprite can only belong to ONE physics system. So you can enable a Sprite for p2 or arcade - but never more than one. It cannot exist in multiple simulations at once. + +Here is how you enable a Sprite for say Ninja physics. You can do it directly on the system like so (here creating a new Circle shape): + +`game.physics.ninja.enableCircle(sprite, radius);` + +Or you can use the physics manager interface (this will create an AABB shape for the sprite, the default): + +`game.physics.enable(sprite, Phaser.Physics.NINJA);` + +In 'enable' calls you can pass in either a single object, a Group or a whole array of them. + +p2 and Arcade running together +------------------------------ + +Why on earth might you want to have both running? Well for a lot of games I would say there is what you could call 'simple' and 'advanced' requirements. For example you could have a nice complex polygon terrain all handled by p2, with a car body with motors / constraints / springs driving happily across it. + +But what if you wanted that car to be able to fire up to shoot some aliens overhead? Assuming you can fit those aliens into clean AABB shapes then it's now entirely possible to have the car itself controlled by p2, driving over a p2 managed landscape, but when you shoot it launches a stream of bullets managed entirely by Arcade Physics, and collision with the aliens who are all running under Arcade Physics too. In short you're leaving p2 to deal with just a handful of complex bodies and motion and not bogging it down with ultra simple requirements. + +I'm not suggesting that all games will need this, but at least you have the option now. + +Great, but what the hell is Ninja Physics? +------------------------------------------ + +While renaming these classes I remembered that I had spent weeks about a year ago working through the physics system that Metanet Software used in their awesome N+ Flash ninja games and porting it to JavaScript. I had shelved it as it was only suitable for certain types of games and didn't play well with Arcade Physics settings (at the time I was trying to merge some of their collision responses with Arcade Physics). But I dug out the old source files and had a look, and sure enough it was pretty much complete. So to test out my theory of Phaser supporting a variety of physics systems I created Ninja Physics from it, and integrated it. + +It's a really nice little physics system, supporting AABB and Circle vs. Tile collision, with lots of defs for sloping, convex and concave tile types. But that's all it does, it's not trying to be anything more really. As you'll see from my the examples it works well, and is really quite fast on mobile too. + +Which one do I use?! +-------------------- + +I've no idea, it depends on your game :) The choice is yours. If you need full-body physics, then p2 obviously. Arcade Physics has proven successful in lots of games so far, so you could carry on using that too. Or maybe if you like what you see re: Ninja's tiles, you could test that out. The important thing is that it's up to you now, and although it requires more careful planning with your game, you can even combine them too. + +Phaser doesn't have all of these physics systems running together wasting CPU, they all start off as 'null' objects and do nothing until explicitly activated. I'm also tweaking the grunt scripts so that the build folder will provide versions of phaser with none, one or all physics systems embedded into the code, so they're not going to waste space either. The plan is to carry on adding support for popular physics systems in, most importantly Box2D and Chipmunk. Again these will be separate libs you can bundle in with phaser, with just a single variable stub in the physics manager. As long as the Body and World objects adhere to a few simple requirements, it will 'just work'. + \ No newline at end of file